I have a 2-dimensional array:
$test = array(
"foo" => array(
'a' => 1,
'b' => 2,
'c' => 3
),
"bar" => array(
'a' => 1,
'b' => 2,
'c' => 3
),
"baz" => array(
'a' => 1,
'b' => 2,
'c' => 3
)
);
I would like to add a field named 'd' with the value 4 to each element of the outer array, so that the resulting array becomes:
array(
"foo" => array(
'a' => 1,
'b' => 2,
'c' => 3,
'd' => 4
),
"bar" => array(
'a' => 1,
'b' => 2,
'c' => 3,
'd' => 4
),
"baz" => array(
'a' => 1,
'b' => 2,
'c' => 3,
'd' => 4
)
)
I’ve tried this:
foreach ( $test as $elem )
{
$elem['d'] = 4;
}
which doesn’t work. What am I doing wrong, and how can I make this work?
Arrays and primitives are passed by value in PHP (though objects are passed by reference). One method to overcome this in a
foreachloop is to access the subarrays by reference in the loop: