Let me prefix this by saying that I know what foreach
is, does and how to use it. This question concerns how it works under the bonnet, and I don\'t want any an
As per the documentation provided by PHP manual.
On each iteration, the value of the current element is assigned to $v and the internal
array pointer is advanced by one (so on the next iteration, you'll be looking at the next element).
So as per your first example:
$array = ['foo'=>1];
foreach($array as $k=>&$v)
{
$array['bar']=2;
echo($v);
}
$array
have only single element, so as per the foreach execution, 1 assign to $v
and it don't have any other element to move pointer
But in your second example:
$array = ['foo'=>1, 'bar'=>2];
foreach($array as $k=>&$v)
{
$array['baz']=3;
echo($v);
}
$array
have two element, so now $array evaluate the zero indices and move the pointer by one. For first iteration of loop, added $array['baz']=3;
as pass by reference.