Code: Select all
<?php
$array1 = array('a' => 1);
$array2 = array('b' => 2);
$array3 = array('c' => 3);
$matrix = array($array1, $array2, $array3);
foreach($matrix as &$array)
$array['d'] = 4;
foreach($matrix as $array)
print_r($array);
?>This should just add the key / value pair ['d'] = 4 to each array.
The expected output is then:
Array ( [a] => 1 [d] => 4 ) Array ( => 2 [d] => 4 ) Array ( [c] => 3 [d] => 4 )
The actual output is:
Array ( [a] => 1 [d] => 4 ) Array ( => 2 [d] => 4 ) Array ( => 2 [d] => 4 )
My guess:
The first foreach loop disrupts the pointer making the second foreach loop point to the last element twice.
Is anyone able to explain this better or create a simpler example where this happens?
(using PHP 5)

