Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: How to modify an array from inside foreach loop (by reference) [duplicate]

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";

like image 942
emersonthis Avatar asked Sep 25 '26 01:09

emersonthis


1 Answers

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);
like image 191
Mark Baker Avatar answered Sep 26 '26 17:09

Mark Baker