What is the differences between array_merge() and array_merge_recursive() functions in PHP ?


Both array_merge() and array_merge_recursive() are PHP functions used to merge two or more arrays into a single array. However, there are some differences between them:

  • array_merge():
  • It merges two or more arrays into a single array.
  • If two or more elements have the same key, the later element will overwrite the previous one.
  • It does not handle multidimensional arrays.
  • It returns a new array.

Example:

$array1 = array('color' => 'red', 2, 4);
$array2 = array('a', 'b', 'color' => 'green', 'shape' => 'trapezoid', 4);
$result = array_merge($array1, $array2);
print_r($result);

Output:

Array
(
    [color] => green
    [0] => 2
    [1] => 4
    [2] => a
    [3] => b
    [shape] => trapezoid
    [4] => 4
)
  • array_merge_recursive():
  • It merges two or more arrays into a single array.
  • If two or more elements have the same key, it will create an array of values for that key.
  • It handles multidimensional arrays.
  • It returns a new array.

Example:

$array1 = array('color' => array('favorite' => 'red'), 2, 4);
$array2 = array('a', 'b', 'color' => array('favorite' => 'green', 'blue'));
$result = array_merge_recursive($array1, $array2);
print_r($result);

Output:

Array
(
    [color] => Array
        (
            [favorite] => Array
                (
                    [0] => red
                    [1] => green
                )

            [0] => blue
        )

    [0] => 2
    [1] => 4
    [2] => a
    [3] => b
)


About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.