Array Functions

PHP array_merge_recursive() Function

Topic: PHP Array ReferencePrev|Next


The array_merge_recursive() function merge one or more arrays into one array recursively.

This function merges the elements of one or more arrays together in such a way that the values of one are appended to the end of the previous one. It returns a new array with merged elements.

The following table summarizes the technical details of this function.

Return Value: Returns the merged array.
Changelog: Since PHP 7.4.0, this function can now be called without any parameter. Previously, at least one parameter has been required.
Version: PHP 4.0.1+


The basic syntax of the array_merge_recursive() function is given with:

array_merge_recursive(array1, array2, ...)

The following example shows the array_merge_recursive() function in action.

// Sample arrays
$array1 = array("pets"=>array("cat", "dog"), "wilds"=>array("lion", "fox"));
$array2 = array("fruits"=>array("apple", "banana"), "lemon", "corn");

// Merging the two array
$result = array_merge_recursive($array1, $array2);


The array_merge_recursive() function accepts the following parameters.

Parameter Description
array1 Optional. Specifies the first array to merge.
array2 Optional. Specifies the second array to merge.
... Optional. Specifies more array to merge.

More Examples

Here're some more examples showing how array_merge_recursive() function basically works:

If the input arrays have the same string keys, then the values for these keys are merged together into an array, and this is done recursively. No overwrite will occur in case of numeric key.

// Sample arrays
$array1 = array("fruits"=>array("a"=>"apple"), 5);
$array2 = array(10, "fruits"=>array("a"=>"apricot", "banana"));

// Merging the two arrays
$result = array_merge_recursive($array1, $array2);
Bootstrap UI Design Templates