PHP, 5.3 non thread safe window, also proven on PHP 5.2.9 on linux.
Sample code:
$test1 = array(
array("val"=>"a"),
array("val"=>"b"),
array("val"=>"c")
);
foreach($test1 as $key => $test)
{
echo $test['val'] . "\n";
}
foreach($test1 as $key => &$test)
{
echo $test['val'] . "\n";
}
foreach($test1 as $key => $test)
{
echo $test['val'] . "\n";
}
output:
a
b
c
a
b
c
a
b
b
Expected output:
a
b
c
a
b
c
a
b
c
So what happens? My first thought was that the array pointer was somehow involved… it wasn’t reset did nothing. Then I thought the reference was somehow changing the values, but no, if I run it with &test again instead of the last one the expected output emerges, however, after the first loop using the reference, any loop WITHOUT the reference will change the last value…. this leaves me completely stumped. Can anyone give me an explanation?
If you’re looping by reference, unset($test) otherwise the reference still exists.
This behaviour is well documented
Warning
Reference of a $value and the last array element remain even after the foreach loop. It is recommended to destroy it by unset().