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?

2
  • It probably has something to do with this: stackoverflow.com/questions/17528280/…, see if you can figure it out. It's too late for me right now. :) Commented Jul 23, 2013 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. Commented Jul 24, 2013 at 0:51

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Then why does $a = array(); $a['foo'] = $a; not produce recursion?
@Jesse just wanted to ask the same :). I think that it's wrong statement. We need to look in PHP sources.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.