Possible Duplicate:
Strange behaviour after loop by reference - Is this a PHP bug?
ideone
code:
<?php
$arr = array(array(1),array(2),array(3));
foreach($arr as &$i) {
print_r($i);
}
foreach($arr as $i) {
print_r($i);
}
output
Array
(
[0] => 1
)
Array
(
[0] => 2
)
Array
(
[0] => 3
)
Array
(
[0] => 1
)
Array
(
[0] => 2
)
Array
(
[0] => 2
)
I know I just need to put an unset($i)
after the first loop to fix it, but I can't really figure out what would cause the 2
to be repeated. It always seems to be the last value that is overwritten with the 2nd to last value. It doesn't seem to happen when the array items are primitives ('scalar' in PHP).
I've ran into this problem a few times with reused variables when someone forgets to unset a reference. Really confused me the first time.