Nolan Hyde
Nolan Hyde

Reputation: 222

PHP variable reference puzzle

run following code:

<?php
$a = array('yes');
$a[] = $a;
var_dump($a);

out put:

array(2) {
  [0]=>
  string(3) "yes"
  [1]=>
  array(1) {
    [0]=>
    string(3) "yes"
  }
}

run following code:

<?php
$a = array('no');
$b = &$a;
$a[] = $b;
$a = array('yes');
$a[] = $a;
var_dump($a);

out put:

array(2) {
  [0]=>
  string(3) "yes"
  [1]=>
  array(2) {
    [0]=>
    string(3) "yes"
    [1]=>
    *RECURSION*
  }
}

I have reassigned value of $a, why there are RECURSION circular references?

Upvotes: 6

Views: 104

Answers (1)

sectus
sectus

Reputation: 15454

To remove reference you need to call unset. Without unset after $a = array('yes'); $a still bounds with $b and they are still references. So the second part has the same behavior as first one.

Note, however, that references inside arrays are potentially dangerous. Doing a normal (not by reference) assignment with a reference on the right side does not turn the left side into a reference, but references inside arrays are preserved in these normal assignments.

http://php.net/manual/en/language.references.whatdo.php

Upvotes: 3

Related Questions