3
I was doing some tests and I realized that the foreach has a strange behavior.
Suppose I have the following array:
$array = array('primeiro', 'segundo', 'terceiro');
When I run one foreach using a reference, and then another without reference foreach (with the same variable), see what happens:
$array = array('primeiro', 'segundo', 'terceiro');
foreach ($array as &$b);
var_dump($array);
foreach ($array as $b);
var_dump($array);
Upshot:
array (size=3)
0 => string 'primeiro' (length=8)
1 => string 'segundo' (length=7)
2 => &string 'terceiro' (length=8)
array (size=3)
0 => string 'primeiro' (length=8)
1 => string 'segundo' (length=7)
2 => &string 'segundo' (length=7)
See that the last element has a different value.
Then two questions arose:
- The last value of
$arrayhas become the penultimate element? - Why, after a
foreachwith variable by reference, the last element is as referenced by the variable (which is after theas)?
Observing: Repair the sign of & in the result.
There’s a nice discussion at the SO gringo about it here
– Caio Felipe Pereira
To ask a creative question when the goal, it seems to me, is the very construction of the question, is really difficult. Questions that come from real problems that people encounter, in general, are much more productive and well accepted by the community.
– Caio Felipe Pereira