Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP combine two associative arrays into one array

$array1 = array("$name1" => "$id1");  $array2 = array("$name2" => "$id2", "$name3" => "$id3"); 

I need a new array combining all together, i.e. it would be

$array3 = array("$name1" => "$id1", "$name2" => "$id2", "$name3" => "$id3"); 

What is the best way to do this?

Sorry, I forgot, the ids will never match each other, but technically the names could, yet would not be likely, and they all need to be listed in one array. I looked at array_merge but wasn't sure if that was best way to do this. Also, how would you unit test this?

like image 300
jsteinmann Avatar asked Nov 01 '12 02:11

jsteinmann


People also ask

How can I merge two arrays in PHP?

The array_merge() is a builtin function in PHP and is used to merge two or more arrays into a single array. This function is used to merge the elements or values of two or more arrays together into a single array.

How do you append an associative array in PHP?

Use the array_merge() Function to Add Elements at the Beginning of an Associative Array in PHP. To add elements at the beginning of an associative, we can use the array union of the array_merge() function.

What is the difference between array_merge () and Array_merge_recursive () in PHP?

The array_merge_recursive() function merges one or more arrays into one array. The difference between this function and the array_merge() function is when two or more array elements have the same key. Instead of override the keys, the array_merge_recursive() function makes the value as an array.


2 Answers

array_merge() is more efficient but there are a couple of options:

$array1 = array("id1" => "value1");  $array2 = array("id2" => "value2", "id3" => "value3", "id4" => "value4");  $array3 = array_merge($array1, $array2/*, $arrayN, $arrayN*/); $array4 = $array1 + $array2;  echo '<pre>'; var_dump($array3); var_dump($array4); echo '</pre>';   // Results:     array(4) {       ["id1"]=>       string(6) "value1"       ["id2"]=>       string(6) "value2"       ["id3"]=>       string(6) "value3"       ["id4"]=>       string(6) "value4"     }     array(4) {       ["id1"]=>       string(6) "value1"       ["id2"]=>       string(6) "value2"       ["id3"]=>       string(6) "value3"       ["id4"]=>       string(6) "value4"     } 
like image 165
Samuel Cook Avatar answered Sep 26 '22 02:09

Samuel Cook


Check out array_merge().

$array3 = array_merge($array1, $array2); 
like image 26
Brad Avatar answered Sep 24 '22 02:09

Brad