143 of 410 menu

The array_merge_recursive Function

The array_merge_recursive function merges two or more arrays together. The difference from the array_merge function becomes apparent when the arrays being merged have identical keys. See the examples.

Syntax

array_merge_recursive(array ...$arrays): array

Example

Let's merge two arrays that have identical keys:

<?php $arr1 = ['a' => 1, 2, 3]; $arr2 = ['a' => 4, 5, 6]; $res = array_merge_recursive($arr1, $arr2); var_dump($res); ?>

Code execution result:

['a' => [1, 4], 2, 3, 5, 6]

Example

For comparison, see how the array_merge function works:

<?php $arr1 = ['a' => 1, 2, 3]; $arr2 = ['a' => 4, 5, 6]; $res = array_merge($arr1, $arr2); var_dump($res); ?>

Code execution result:

['a' => 1, 2, 3, 5, 6]

See Also

  • the array_merge function,
    which also merges arrays
  • the array_combine function,
    which merges two arrays into one associative array
byenru