2

Possible Duplicate:
How to modify an array's values by a foreach loop?

Why doesn't this work?

$user_list_array = array(
    1 => array( "first_name" => "Jim" ),
    2 => array( "first_name" => "Bob" )
)

foreach ($user_list_array as $item ) {
    echo $item["first_name"];
    $item["last_name"] = "test";
} 

var_dump($user_list_array );

I can get the "first_name"s back, but can't add the "last_name";

Community
  • 1
  • 1
emersonthis
  • 32,822
  • 59
  • 210
  • 375

4 Answers4

6

You're modifying $item, which is a copy of the relevant entry fro $user_list_array

EITHER: (modify the original array)

foreach ($user_list_array as $key => $item ) { 
    echo $item["first_name"]; 
    $user_list_array[$key]["last_name"] = "test"; 
} 

OR: (by reference)

foreach ($user_list_array as &$item ) { 
    echo $item["first_name"]; 
    $item["last_name"] = "test"; 
} 
unset($item);
Mark Baker
  • 209,507
  • 32
  • 346
  • 385
  • You would not happend to have a benchmark on the performance between the two ? – Antoine Hedgecock Sep 29 '12 at 13:06
  • No I don't have a benchmark, though easy enough to run. At a guess, I'd think it would be the "by reference" option, because it doesn't need to handle both key and value in the foreach; but that is just a guess – Mark Baker Sep 29 '12 at 13:09
  • @MarkBaker Without knowing the exact stats, do you thinks it's problematic to loop over 1000 users this way? I know foreach loops can slow things down, but I don't know how else to do this. – emersonthis Sep 29 '12 at 13:18
  • Loops are a natural part of most programming languages, and shouldn't be avoided purely because there's a risk of slow execution... any potential performance issue is dependent on what's done in the loop. In this case, a simple echo and simple modification of the array entry isn't a great deal, even over 1000 iterations. A third option, which might be slightly faster in some cases would be using array_map() or array_walk() with a closure; but I don't honestly think you need to worry excessively in this case – Mark Baker Sep 29 '12 at 13:40
3
foreach ($user_list_array as &$item ) {
    echo $item["first_name"];
    $item["last_name"] = "test";
} 

Adding & before $item will pass the array by reference which means that any modifications you make to it will be saved.

0

It didn't work because you were not modifying the actual array, this should do the trick.

$user_list_array = array(
    1 => array( "first_name" => "Jim" ),
    2 => array( "first_name" => "Bob" )
)

foreach ($user_list_array as $id => $item ) { 
    echo $item["first_name"]; 
    $user_list_array[$id]["last_name"] = "test"; 
} 
0

You should be modifying the original array, not the tmp variable $item the loop creates. You could do it like that

foreach ($user_list_array as $key = $val) {
    echo $val["first_name"];
    $user_list_array[$key]["last_name"] = "test";
} 
Havelock
  • 6,913
  • 4
  • 34
  • 42