I was doing a script where I needed to work with every single value of an array, so I helped myself with the trick of using the assignment operator in the value parameter of the foreach in order to edit the array value directly, and I noticed that every last value of the foreach give a strange problem.
That's the PHP script:
<?php
$array = array('test1', 'test2', 'test3', 'test4');
var_dump($array);
echo "<br />";
foreach ($array as &$value)
{
// do something
$value = $value . "foo";
}
var_dump($array);
echo "<br />";
foreach ($array as $value)
{
echo $value . "<br />";
}
And that's the output:
array(4) { [0]=> string(5) "test1" [1]=> string(5) "test2" [2]=> string(5) "test3" [3]=> string(5) "test4" }
array(4) { [0]=> string(8) "test1foo" [1]=> string(8) "test2foo" [2]=> string(8) "test3foo" [3]=> &string(8) "test4foo" }
test1foo
test2foo
test3foo
test3foo
As you notice, the var_dump of the array after the foreach, in the last value, there's the assignment operator in front of the type of value (string).
And when I try to output every value of the array, it doesn't give me the last value "test4foo" but it repeat the precedent value (penultimate).
Is it a bug? Can anyone explain it?