0

This is a array that i printed out in PHP

Array ( [0] => Array ( [friend_id] => 1 [name] => parker[email] => parker@gmail.com)[1] => Array ( [friend_id] => 2 [name] => peter [email] => peter@hotmail.com) )

Can i know how to use loop in php to add a new item/param inside the array like this

Array ( [0] => Array ( [friend_id] => 1 [name] => parker[email] => parker@gmail.com [NEWOBJECT] => newvalue)[1] => Array ( [friend_id] => 2 [name] => peter [email] => peter@hotmail.com [NEWOBJECT] => newvalue) )
Dray
  • 902
  • 8
  • 25
Mavichow
  • 1,137
  • 16
  • 37

2 Answers2

1

No need for loop you can just add by this:

<?
 $arr =  Array ( [0] => Array ( [friend_id] => 1 [name] => parker[email] => parker@gmail.com)[1] => Array ( [friend_id] => 2 [name] => peter [email] => peter@hotmail.com) );

 $arr[0]['NEWOBJECT'] = 'blablabla';
 $arr[1]['NEWOBJECT'] = 'blablabla';
?>

But when you have to do this more than 2 times of course this would help:

<?

$arr =  Array ( [0] => Array ( [friend_id] => 1 [name] => parker[email] => parker@gmail.com)[1] => Array ( [friend_id] => 2 [name] => peter [email] => peter@hotmail.com) );

 foreach($arr as $key => $value){
    $arr[$key]['NEWOBJECT'] = 'blablabla';
 }

?>
botenvouwer
  • 3,658
  • 7
  • 38
  • 67
0

You could use a foreach loop to iterate over the items and add in the new keys, in the following manner.

foreach($array as &$item) {
    $item['newkey'] = "New Value";
}

Note the use of the ampersand(&) operator. This ensures we have a reference to $item and not a copy, meaning changes will affect the original $item.

xenon
  • 1,456
  • 18
  • 31