3
$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?

Jesse
  • 6,725
  • 5
  • 40
  • 45
  • It probably has something to do with this: http://stackoverflow.com/questions/17528280/why-does-reference-assigning-an-arrays-element-modify-the-array/17528610#17528610, see if you can figure it out. It's too late for me right now. :) – deceze Jul 23 '13 at 21:15
  • I tried to imagine what the symbol tables would look like as the code executes, as per the answer you linked to, but I only arrive at the behaviour I expected, not the behaviour I'm seeing. – Jesse Jul 24 '13 at 00:51

1 Answers1

0

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.

matt2000
  • 1,064
  • 11
  • 17