PHP Function: array_merge_recursive
The array_merge_recursive function in PHP is a powerful tool for combining arrays and preserving the key-value pairs within them. This function can be used to
The array_merge_recursive() function in PHP combines two or more arrays into one. Its defining feature is how it handles overlapping string keys: instead of letting a later value overwrite an earlier one, it merges both values into a sub-array, recursing into nested arrays as it goes. This makes it the right tool when you want to keep every value rather than have the last array win.
This page covers the syntax and parameters, how the recursive merge actually works, how it differs from array_merge(), a real-world use case, and the gotchas to watch for.
Syntax
array_merge_recursive(array $array1, array ...$arrays): arrayParameters
array1: The first input array....$arrays: One or more additional arrays to merge.
Return Value
Returns the resulting merged array.
How does array_merge_recursive work?
The function applies two different rules depending on the key type:
- String keys that appear in more than one array are combined. If both values are scalars, they are gathered into a new sub-array; if both are arrays, the function recurses and merges them at the next level down.
- Integer (numeric) keys are never overwritten. Each numeric-keyed element is appended and renumbered, so nothing is lost and the result is re-indexed from
0.
This is why the function is "recursive": whenever it meets two arrays under the same string key, it dives in and repeats the same merge logic on their contents.
Note: Unlike array_merge(), which overwrites values for overlapping string keys and reindexes numeric keys, array_merge_recursive() merges overlapping string keys into nested arrays while preserving every value.
Here's an example of how array_merge_recursive works:
PHP example of array_merge_recursive function
The output of this code will be:
Array
(
[color] => Array
(
[favorite] => Array
(
[0] => red
[1] => green
)
[0] => blue
)
[0] => 5
[1] => 10
)As you can see, the array_merge_recursive function has merged the overlapping keys in the input arrays into sub-arrays.
array_merge() vs. array_merge_recursive()
Seeing the two functions side by side makes the difference concrete:
<?php
$defaults = ["roles" => ["user"], "name" => "Guest"];
$overrides = ["roles" => ["editor"], "name" => "Ann"];
print_r(array_merge($defaults, $overrides));
print_r(array_merge_recursive($defaults, $overrides));
?>Array // array_merge(): later value wins
(
[roles] => Array
(
[0] => editor
)
[name] => Ann
)
Array // array_merge_recursive(): both values kept
(
[roles] => Array
(
[0] => user
[1] => editor
)
[name] => Array
(
[0] => Guest
[1] => Ann
)
)Notice that even name, a simple string, became an array ["Guest", "Ann"]. That is the key gotcha covered below: recursive merging turns every repeated string key into a list, whether you wanted that or not.
When to use array_merge_recursive
Reach for this function when collecting values is the goal rather than choosing one. A common case is grouping data — for example, building a map of a category to all of its items:
<?php
$result = [];
$products = [
["category" => "fruit", "name" => "apple"],
["category" => "fruit", "name" => "pear"],
["category" => "vegetable", "name" => "carrot"],
];
foreach ($products as $product) {
$result = array_merge_recursive(
$result,
[$product["category"] => [$product["name"]]]
);
}
print_r($result);
?>Array
(
[fruit] => Array
(
[0] => apple
[1] => pear
)
[vegetable] => Array
(
[0] => carrot
)
)Gotchas
- String keys are merged, integer keys are appended. A repeated string key produces a sub-array even when both values are scalars. If you instead want later values to overwrite earlier ones, use
array_merge()orarray_replace_recursive(). - Numeric keys are not preserved. Integer keys are always renumbered from
0, so you cannot usearray_merge_recursive()to merge two arrays by their numeric keys. Use the+(union) operator if you need the keys kept as-is. - It only descends into arrays. If one side is a scalar and the other is an array under the same key, both are simply gathered into a list; the scalar is not merged into the array.
Related functions
array_merge()— flat merge where later string keys overwrite earlier ones.array_replace_recursive()— recurses like this function but replaces values instead of collecting them.array_combine()— builds an array from a separate keys array and values array.
Conclusion
The array_merge_recursive() function is the right choice when you want to combine values under shared string keys instead of overwriting them — grouping, aggregating, or accumulating data across arrays. Keep its two rules in mind (string keys merge into lists, integer keys are re-indexed), and choose array_merge() or array_replace_recursive() when you need last-value-wins behavior instead.