Updating arrays in an array using foreach

I am trying to update an array, but the array contains arrays.

As an 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 of 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 to the new one?

+4
source share
3 answers

use the link:

foreach($data as &$onearray) {
     $onearray['alive'] = 'true';
}
unset($onearray)

and clear the link after that, so further code will not ruin it


To be able to directly modify array elements in a loop, $ value is preceded with &. In this case, a value will be assigned to the link.

see foreach-reference for more: http://us2.php.net/manual/en/control-structures.foreach.php

+5
source

? :

foreach($data as $key => $onearray){
     $data[$key]['alive'] = 'true';
}

( , $onearray )

:

for($i = 0; $i < count($data); $i++) {
    $data[$i]['alive'] = 'true';
}
+7

Use the built-in array_walk function - apply a user function to each member of the array

<?php
$fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple");

function test_alter(&$item1, $key, $prefix)
{
    $item1 = "$prefix: $item1";
}

function test_print($item2, $key)
{
    echo "$key. $item2<br />\n";
}

echo "Before ...:\n";
array_walk($fruits, 'test_print');

array_walk($fruits, 'test_alter', 'fruit');
echo "... and after:\n";

array_walk($fruits, 'test_print');
?>

Exit

Before ...:
d. lemon
a. orange
b. banana
c. apple
... and after:
d. fruit: lemon
a. fruit: orange
b. fruit: banana
c. fruit: apple
+1
source

All Articles