Skip to content

Modifying a copied by-ref iterated array resets the array position #11244

Closed
@survik1

Description

@survik1

Description

Hello, we are finally pushing our code to PHP 8 and I have encountered this BC break which seems more like bug than feature to me. This behavior is still present in 8.2 and the change was not documented (unless i missed it ofc).

https://3v4l.org/aNejW

<?php

$_ENV = [
    'ZASIS_UI_BACKGROUNDCOLOR' => '#FFF1EC',
    'ZASIS_UI_INFOPANEL_ENABLE' => '1',
    'ZASIS_UI_INFOPANEL_TEXT' => 'DEBUG IS ON',
    'ZASIS_UI_INFOPANEL_BACKGROUNDCOLOR' => '#F44',
];

$arr = [
    'ui' => [
        'backgroundColor' => 'ZASIS_UI_BACKGROUNDCOLOR',
        'infoPanel' => [
            'enable' => 'ZASIS_UI_INFOPANEL_ENABLE',
            'text' => 'ZASIS_UI_INFOPANEL_TEXT',
            'fontColor' => 'ZASIS_UI_INFOPANEL_FONTCOLOR',
            'backgroundColor' => 'ZASIS_UI_INFOPANEL_BACKGROUNDCOLOR',
        ]
    ]
];

function loadEnv(&$data): void
{
    if (is_array($data)) {
        foreach ($data as $key => &$value) {
            try {
                loadEnv($value);
            } catch (\InvalidArgumentException $e) {
                unset($data[$key]);
            }
        }
    } elseif (array_key_exists($data, $_ENV)) {
        $data = $_ENV[$data];
    } else {
        throw new \InvalidArgumentException();
    }
}
loadEnv($arr);
print_r($arr);

Output in PHP >=8.0:

Array
(
    [ui] => Array
        (
            [backgroundColor] => #FFF1EC
            [infoPanel] => Array
                (
                    [backgroundColor] => #F44
                )

        )

)

Output in PHP >=7.1 <8.0:

Array
(
    [ui] => Array
        (
            [backgroundColor] => #FFF1EC
            [infoPanel] => Array
                (
                    [enable] => 1
                    [text] => DEBUG IS ON
                    [backgroundColor] => #F44
                )

        )

)

PHP Version

PHP 8.2.6

Operating System

No response

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions