0

I've seen many questions about this (one of them here)

$a = array('a', 'b', 'c', 'd');

foreach ($a as &$v) { }
foreach ($a as $v) { }

print_r($a);

and I get the answers, you shouldn't be recycling the $v variable name. But..!

Can someone explain to me why this code

$a = array('a', 'b', 'c', 'd');

foreach ($a as &$v) { }

var_dump($a);

prints this (note that the last element is a reference)?

array(4) {
  [0]=>
  string(1) "a"
  [1]=>
  string(1) "b"
  [2]=>
  string(1) "c"
  [3]=>
  &string(1) "d"
}

I expect it to be just a value, only $v should be a reference. In other words, I'm dealing with the same behaviour as described (and well documented) in the quoted question, although I'm not reusing $v variable incorrectly.

37
  • 1
    @Vali, does this make it a little clearer what's going on? 3v4l.org/2VZYG
    – Chris Haas
    Commented Apr 15 at 13:28
  • 1
    @Vali, you can chech this collection of questions: stackoverflow.com/questions/3737139/… and PHP's References Explained page.
    – shingo
    Commented Apr 15 at 14:02
  • 1
    @Vali, we can remove the foreach from this discussion if it helps, too: 3v4l.org/5WPsX
    – Chris Haas
    Commented Apr 15 at 15:46
  • 1
    @ChrisHaas Yes, it makes even less sense that way :D Or same but it's more clear what I ment.
    – Vali
    Commented Apr 15 at 15:48
  • 2
    I'll point to one more bit of documentation about references. "People will commonly say that “$b is a reference to $a”. However, this is not quite correct, in that references in PHP have no concept of directionality. After $b =& $a, both $a and $b reference a common value, and neither of the variables is privileged in any way." They further go on to arrays explaining why this happens but do include the statement "Intuitively this behavior is wrong".
    – Chris Haas
    Commented Apr 15 at 18:25

0

Browse other questions tagged or ask your own question.