2

I have an issue which I can't explain for now. It's well-known that foreach in PHP works with copy of array, i.e. it copies the array first and then iterates through it. All fine and dandy. But this is weird:

$array = ['foo' => 1];
foreach($array as $k => & $v)
{
   $array['bar'] = 2;
   echo $v;
}

This will result in 1. Next, if we add another element to the array (just to be sure, we'll run this code in separate file so it doesn't affect the refcount or anything else for these test cases):

$array = ['foo' => 1, 'bar' => 2];
foreach($array as $k => & $v)
{
   $array['baz'] = 3;
   echo $v;
}

Bingo! We have 1, 2 and 3 printed. Why? If PHP works on the array by reference, then it should result in 1 and 2 for the first case. And if PHP works with a copy, then it should result in 1 and 2 (without 3) for the second case.

My question is a continuation for this great question. Yes, I'm aware about how copying works. But we have same refcount for both cases. Why the results are different, is currently beyond my understanding.

Community
  • 1
  • 1
Alma Do
  • 37,009
  • 9
  • 76
  • 105

0 Answers0