I have a simple multidimensional array. I modify it - ie. I add data to it - in a foreach loop, accessing its elements by reference:
$array = array(
array('id' => 12, 'name' => 'John1', 'surname' => 'Smith1'),
array('id' => 13, 'name' => 'John2', 'surname' => 'Smith2'),
array('id' => 14, 'name' => 'John3', 'surname' => 'Smith3'),
array('id' => 15, 'name' => 'John4', 'surname' => 'Smith4'),
);
foreach($array as &$a) {
$a['middlename'] = 'Robert';
}
Now what's below shows that $array
is perfectly in order:
print('<pre>'.print_r($array,true).'</pre>');
results in:
Array
(
[0] => Array
(
[id] => 12
[name] => John1
[surname] => Smith1
[middlename] => Robert
)
[1] => Array
(
[id] => 13
[name] => John2
[surname] => Smith2
[middlename] => Robert
)
[2] => Array
(
[id] => 14
[name] => John3
[surname] => Smith3
[middlename] => Robert
)
[3] => Array
(
[id] => 15
[name] => John4
[surname] => Smith4
[middlename] => Robert
)
)
But while I loop though it, internal pointer stops right before last element:
foreach($array as $a) {
print('<pre>'.print_r($a['id'],true).'</pre>');
}
outputs:
12
13
14
14
Any hints what's going on?
UPDATE: The answer I picked is correct and moreover I found this: PHP Pass by reference in foreach Thx, SO.