PHP array_merge_recursive() Function

Quick summary: The PHP array_merge_recursive() function merges arrays recursively, combining values with the same keys.

PHP array_merge_recursive() Syntax

array_merge_recursive(array ...$arrays): array
PHP

PHP array_merge_recursive() Basic examples

var_dump(array_merge_recursive(['a'=>['x'=>1]], ['a'=>['y'=>2]]));
PHP
Output:
array(1) {
  ["a"]=> array(2) {
    ["x"]=> int(1)
    ["y"]=> int(2)
  }
}

Merges nested arrays instead of overwriting them.

PHP array_merge_recursive() Real-world usage

$config1 = ['db'=>['host'=>'localhost']];
$config2 = ['db'=>['port'=>3306]];
var_dump(array_merge_recursive($config1, $config2));
PHP
Output:
array(1) {
  ["db"]=> array(2) {
    ["host"]=> string(9) "localhost"
    ["port"]=> int(3306)
  }
}

Combines configuration arrays.

PHP array_merge_recursive() Edge cases

var_dump(array_merge_recursive(['a'=>1], ['a'=>2]));
PHP
Output:
array(1) {
  ["a"]=> array(2) {
    [0]=> int(1)
    [1]=> int(2)
  }
}

Scalar values become arrays when keys collide.

PHP array_merge_recursive() Common mistakes

Unexpected array nesting

Values with the same key are combined into arrays.

Incorrect
array_merge_recursive(['a'=>1], ['a'=>2]);
Correct
array_merge(['a'=>1], ['a'=>2]);

Use array_merge if overwriting is desired.

PHP array_merge_recursive() Frequently Asked Questions

What does array_merge_recursive() do in PHP?

array_merge_recursive() merges arrays recursively, combining values into arrays when keys match.

How does array_merge_recursive() handle duplicate keys?

Values with the same key are merged into an array instead of overwritten.

What happens to numeric keys in array_merge_recursive()?

Numeric keys are appended without overwriting.

Does array_merge_recursive() modify original arrays?

No, it returns a new merged array.

What is the difference between array_merge() and array_merge_recursive()?

array_merge() overwrites values, while array_merge_recursive() combines them into arrays.

Can array_merge_recursive() create nested arrays?

Yes, duplicate keys result in nested arrays.

Is array_merge_recursive() suitable for configuration merging?

Sometimes, but it can create unexpected nested arrays.

What is a real-world use case of array_merge_recursive()?

Merging multi-dimensional arrays where all values should be preserved.

Can array_merge_recursive() cause data structure issues?

Yes, it may create deeply nested arrays unintentionally.

Is array_merge_recursive() fast?

Performance is good but depends on array size and depth.

Can array_merge_recursive() be used with associative arrays?

Yes, it is commonly used with associative arrays.

What is an alternative to array_merge_recursive()?

Use custom merge logic or array_replace_recursive() depending on needs.

PHP array_merge_recursive() Related PHP Functions