In this article, we will learn about array_merge(), a predefined PHP array function. The array_merge() is utilized to combine at least two more arrays into a single array. This function is utilized to combine the components of at least two arrays together into a single array.
This function works to merge the elements of one or more arrays together in such a way so that the values of later array are appended to the end of the former array.
Let's test this with a simple example.
<?php $array1 = array("name" => "alex", 2 ); $array2 = array("a", "b", "department" => "accounting", "id" => 13, 4); $res = array_merge($array1, $array2); print_r($res); ?>
Array ( [name] => alex  => 2  => a  => b [department] => accounting [id] => 13  => 4 );
In the above example, we have declared two arrays and merging them to result in a single array by array_merge() function.
In the event that if the arrays have similar string keys, then the later value for that key will overwrite the previous one. But in case of the arrays contain numeric keys, the later value won't overwrite the first one, yet will be appended.
Let's understand the above concept with an example.
<?php $array1 = array("name" => "alex", 2 ); $array2 = array("a", "b", "name" => "jack", "id" => 18, 2); $result = array_merge($array1, $array2); print_r($result); ?>
Array ( [name] => jack  => 2  => a  => b [id] => 18  => 2 )