I want to add a value to an array while foreaching it :
foreach ($array as $cell) {
if ($cell["type"] == "type_list") {
$cell["list"] = $anObject;
error_log(print_r($cell, TRUE), 0);
}
error_log(print_r($array, TRUE), 0);
The first printr is ok but the object added disapear when I leave the loop ant print the array.
I guess this is a normal behaviour, what is the best way to work around this "feature" ?
When you iterate over the array,
$cell
is a copy of the value, not a reference so changing it will not effect the value in the array.You should either use
&
to make the$cell
a reference:Or access the array items directly using an index.
Just call
$cell
by reference like this:And it should retain the value. Passing by reference.