$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?
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.
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.
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.
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" }
Check out array_merge()
.
$array3 = array_merge($array1, $array2);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With