简体   繁体   中英

PHP Strange behaviour with recursive arrays

$array = array();
$array[ 'recursive' ] =& $array;

$array[ 'foo' ] = $array;

'foo' was assigned by value to $array , which should copy $array , which did not have a 'foo' key at the time, so I expect the situation to now be something like:

$array = array(
    'recursive' => &$array,
    'foo'       => array(
        'recursive' => &$array
    ),
)

But if I now do:

var_dump( isset( $array[ 'foo' ][ 'foo' ][ 'foo' ] ) );

I get:

bool(true)

I don't understand why this is.

If I create an intermediate variable for the assignment of 'foo' , like this:

$array = array();
$array[ 'recursive' ] =& $array;

$blah = $array;
$array[ 'foo' ] = $blah;

var_dump( isset( $array[ 'foo' ][ 'foo' ][ 'foo' ] ) );

I get:

bool(false)

I understand why the 'recursive' key would be infinitely deep, because that was assigned by reference, but why the 'foo' key, which was assigned by value? How can creating an intermediate variable change behaviour for things handled by value?

Because when you do $array['foo'] = $array, the interpreter first adds the 'foo' index to the $array value, then puts that newly updated array inside $array['foo'].

When you use an intermediate $blah, you've stored an unmodified copy of $array from before the 'foo' key was created. The intermediate doesn't change the behavior, it stores a copy of the value at the moment in time that the intermediate is created, just as it should.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM