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 foreach
loop is to access the subarrays by reference in the loop:
// Call $elem by reference with &
foreach ( $test as &$elem ) {
$elem['d'] = 4;
}
print_r($test);
array(3) {
["foo"]=>
array(4) {
["a"]=>
int(1)
["b"]=>
int(2)
["c"]=>
int(3)
["d"]=>
int(4)
}
...
}
$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
)
);
foreach($test as $key => $val)
$test[$key]['d'] = 4;
print_r($test);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With