I'm trying to update an array but the array contains arrays.
For a example,
$data = array(
array('name'=>'John','age'=>'19','alive'=>'false'),
array('name'=>'Bob','age'=>'32','alive'=>'false'),
array('name'=>'Kate','age'=>'22','alive'=>'false'),
);
I need to add another element to all these arrays.
I tried using foreach
foreach($data as $onearray){
$onearray['alive'] = 'true';
}
Do I need to create a new array and add all updated arrays back to new one?
Did you try using the data array key? Like so:
foreach($data as $key => $onearray){
$data[$key]['alive'] = 'true';
}
( Notice the $onearray never gets used )
Even faster would be:
for($i = 0; $i < count($data); $i++) {
$data[$i]['alive'] = 'true';
}
use the referencing:
foreach($data as &$onearray) {
$onearray['alive'] = 'true';
}
unset($onearray)
and clean up the reference afterwards, so further code will not mess it up
In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference.
see foreach-reference for more: http://us2.php.net/manual/en/control-structures.foreach.php
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