PHP Function Reference

PHP array_merge_recursive() Function



The PHP array_merge_recursive() function merges the elements of one or more arrays together such that the values of one are appended to the end of the previous one and returns the resulting array.

If the input arrays have the same string keys, then the values for these keys are merged together into an array recursively. If, however, the arrays have the same numeric key, the later value will not be merged together into an array recursively, but will be appended.

Values in the input arrays with numeric keys will be renumbered with incrementing keys starting from zero in the result array.

Syntax

array_merge_recursive(arrays)

Parameters

arrays Optional. Specify a variable list of arrays to merge.

Return Value

Returns the resulting array. If called without any arguments, returns an empty array.

Exceptions

NA.

Example:

The example below shows the usage of array_merge_recursive() function.

<?php
$Arr1 = array(10, 20, "Red" => 1, 
              "others"=>array("favorite"=> "Green", "Blue"));
$Arr2 = array(20, "Red"=>2, 
              "others"=>array("favorite"=> "Pink"));

//merging Arr1 and Arr2
$Arr3 = array_merge_recursive($Arr1, $Arr2);

//displaying the result
print_r($Arr3);
?>

The output of the above code will be:

Array
(
    [0] => 10
    [1] => 20
    [Red] => Array
        (
            [0] => 1
            [1] => 2
        )

    [others] => Array
        (
            [favorite] => Array
                (
                    [0] => Green
                    [1] => Pink
                )

            [0] => Blue
        )

    [2] => 20
)

Example:

Consider the example below where an empty array is merged with another array.

<?php
$Arr1 = array();
$Arr2 = array("John"=>"London");

//merging Arr1 and Arr2
$Arr3 = array_merge_recursive($Arr1, $Arr2);

//displaying the result
print_r($Arr3);
?>

The output of the above code will be:

Array
(
    [John] => London
)

Example:

Consider one more example where non-array types are merged using this function.

<?php
$str = "John";
$Arr1 = array("Marry"=>"Paris");

//merging str and Arr1
$Arr2 = array_merge_recursive((array)$str, $Arr1);

//displaying the result
print_r($Arr2);
?>

The output of the above code will be:

Array
(
    [0] => John
    [Marry] => Paris
)

❮ PHP Array Reference