I was doing some testing and I noticed that foreach
behaves oddly.
Suppose I have the following array
:
$array = array('primeiro', 'segundo', 'terceiro');
When I run a foreach
using a reference, and then another foreach without a reference (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);
Result:
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 changed.
Then two questions came up:
- Is the last value of
$array
given the value of the penultimate element? - Why, after a% with% with variable by reference, the last element is as referenced by the variable (which is after
foreach
)?
Note : Repair the as
sign in the result.