Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating arrays in an array using foreach

Tags:

arrays

php

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?

like image 333
Naveen Gamage Avatar asked Dec 11 '22 09:12

Naveen Gamage


2 Answers

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';
}
like image 176
Anja Avatar answered Dec 26 '22 08:12

Anja


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

like image 37
floww Avatar answered Dec 26 '22 09:12

floww