Skip to content
Tutorials Center
My learning

Topics

PHP Reference ยท Array Functions

PHP array_merge_recursive() function

Reference for PHP array_merge_recursive(): merge arrays deeply, why duplicate string keys turn into arrays, and when array_replace_recursive() is a better fit.

The array_merge_recursive() function merges arrays like array_merge(), but when two arrays share a string key it does not overwrite the earlier value. It combines both values into an array under that key, descending into nested arrays as it goes.

That surprises many people: merging two configuration arrays with the same scalar key gives you a list of both values instead of the newer one. If you want "later wins" at every depth, use array_replace_recursive().

PHP
$r = array_merge_recursive(["a" => 1], ["a" => 2]);
print_r($r); // ["a" => [1, 2]]

Try it

PHP Duplicate keys become lists

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

PHP Compared with array_replace_recursive()

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Syntax

PHP
array_merge_recursive(array ...$arrays): array
Name Description
...$arrays Zero or more arrays to merge, from left to right.

Return value: the merged array. With no arguments, an empty array.

Errors / Exceptions: a TypeError if any argument is not an array.

Usage notes

  • Same string key, scalar values: the values are collected into an array, so "size" => 10 and "size" => 12 become "size" => [10, 12].
  • Same string key, array values: the arrays are merged recursively using the same rules.
  • Integer keys are appended and renumbered, exactly like array_merge().
  • Not a settings merger. For "override defaults with user values" use array_replace() for one level or array_replace_recursive() for nested data.
  • Result types change. A key that was a string in one input may become an array in the output, which can break code that expects scalars.
  • Input arrays are not modified. Since PHP 7.4 it can be called with no arguments.