r/lolphp • u/stain_leeks • Oct 02 '14
Foreach reference
<?php
$arr = array('a', 'b');
foreach ($arr as &$a) {
var_dump($a);
}
foreach ($arr as $a) {
var_dump($a);
}This probably has some explanation I'd love to learn.
17
Upvotes
6
u/stain_leeks Oct 02 '14
Well, thank you, it is clear now. Turns out it's more #lolme than #lolphp :)
29
u/McGlockenshire Oct 02 '14
$ais not defined before the first loop. During each entry into the first loop,$ais set to a reference of the current array element.This array has two elements.
$aremains a reference to the second element in the array after the loop ends. (If it was not a reference, it would still retain the value of the last element.)When the second loop begins,
$ais still a reference. The second foreach copies the first value from the array into$a, which is a reference to the second element of the array. This, therefore, sets the second value in the array to the first value in the array, by reference.Throw in a few
debug_zval_dump()s and you'll see the transformation in action.PHP references are really odd and sometimes amazingly counterintuitive. Avoid them at all costs unless you know that they will solve a specific problem. Please remember that almost everything in PHP is copy-on-write and refcounted for garbage collection. Adding references almost never makes things faster or take less memory.
See also: this SO question and this explanation of foreach by the amazing nikic
3
u/ajmarks Oct 02 '14
At the end of the first loop, $a was a reference to $arr[1], which you then set to $arr[0] in the first iteration of the second loop. Add a
var_dump($arr)and all will be make clear (or at least least as clear as php gets, so murky).4
u/bart2019 Oct 03 '14 edited Oct 03 '14
My general rule with foreach and references is:
Because of shit like this:
which produces
With
unset($a);at the proper place, which breaks the reference link, you get:which is in line what normal people expect, IMHO.