PHP array_merge_recursive: Merge Arrays Deeply

php array_merge_recursive

PHP array_merge_recursive joins two or more arrays into one nested array and keeps all values with their keys.

Syntax of array_merge_recursive in PHP

The array_merge_recursive function adds values from one array into another and forms nested arrays for repeated keys.

Here is the syntax:

array_merge_recursive(array $array1, array $array2, array ...$arrays): array

This function takes each key from the arrays and groups their values together into one combined array with nested arrays.

Here is a quick example:

$array1 = ["a" => "red", "b" => "blue"];
$array2 = ["a" => "green", "c" => "yellow"];
$result = array_merge_recursive($array1, $array2);
print_r($result);

This example shows that the function puts both values under the same key and creates a nested array for that key.

Here is the output:

Array
(
[a] => Array
(
[0] => red
[1] => green
)

[b] => blue
[c] => yellow
)

Nested Arrays Merging with array_merge_recursive in PHP

When both arrays have the same key, this function places all values under that key and forms nested arrays automatically.

For example:

$array1 = ["colors" => ["red", "blue"]];
$array2 = ["colors" => ["green", "yellow"]];
$result = array_merge_recursive($array1, $array2);
print_r($result);

The output:

Array
(
[colors] => Array
(
[0] => red
[1] => blue
[2] => green
[3] => yellow
)

)

This example shows that PHP joins inner arrays under the same key and returns a new array that holds all values.

The Difference Between array_merge and array_merge_recursive

array_merge replaces values of matching keys with new ones, while array_merge_recursive groups all values under the same key.

Aspectarray_mergearray_merge_recursive
Matching KeysReplaces old valueCreates nested array of values
Non Matching KeysAdds valueAdds value
Result StructureFlat arrayNested array

Use array_merge when you want the last value to replace the previous value. Use array_merge_recursive when you want all values together.

Examples of array_merge_recursive in PHP

Combine two arrays with the same keys:

$array1 = ["fruit" => "apple"];
$array2 = ["fruit" => "banana"];
$result = array_merge_recursive($array1, $array2);
print_r($result);

This example shows how the function groups both values under one key and gives you a nested array with all values.

The output:

Array
(
[fruit] => Array
(
[0] => apple
[1] => banana
)

)

Combine multiple arrays with different keys:

$array1 = ["a" => 1];
$array2 = ["b" => 2];
$array3 = ["a" => 3, "c" => 4];
$result = array_merge_recursive($array1, $array2, $array3);
print_r($result);

This example shows how PHP combines values from many arrays into one and puts them under each key without loss of any data.

The output:

Array
(
[a] => Array
(
[0] => 1
[1] => 3
)

[b] => 2
[c] => 4
)

Combine arrays with inner arrays:

$array1 = ["data" => ["x" => 10]];
$array2 = ["data" => ["y" => 20]];
$result = array_merge_recursive($array1, $array2);
print_r($result);

This example shows how the function joins inner arrays and keeps all nested values under the same key without overwriting.

The output:

Array
(
[data] => Array
(
[x] => 10
[y] => 20
)

)

Combine arrays of different depths:

$array1 = ["config" => ["db" => ["host" => "localhost"]]];
$array2 = ["config" => ["db" => ["port" => 3306]]];
$result = array_merge_recursive($array1, $array2);
print_r($result);

This example shows how PHP handles arrays with deep levels and returns a nested array with all the information kept intact.

The output:

Array
(
[config] => Array
(
[db] => Array
(
[host] => localhost
[port] => 3306
)

)

)

Wrapping Up

You learned what array_merge_recursive does and how it groups values from arrays under one key.

Here is a quick recap:

  • array_merge replaces values with new ones, and array_merge_recursive groups all values under one key to form nested arrays.

FAQs

What is PHP array_merge_recursive used for?

PHP array_merge_recursive combines values from two or more arrays. It merges nested arrays instead of replacing them. Example:
$array1 = array("a" => "red", "b" => "green");
$array2 = array("a" => "blue", "c" => "yellow");

$result = array_merge_recursive($array1, $array2);
print_r($result);
Output:
Array
(
    [a] => Array
        (
            [0] => red
            [1] => blue
        )

    [b] => green
    [c] => yellow
)

What is the difference between array_merge and array_merge_recursive?

  • array_merge: Replaces values with the same key.
  • array_merge_recursive: Combines values into arrays instead of replacing.
Example:
$a = array("x" => "one");
$b = array("x" => "two");

print_r(array_merge($a, $b));
print_r(array_merge_recursive($a, $b));
Output:
array_merge:
Array
(
    [x] => two
)

array_merge_recursive:
Array
(
    [x] => Array
        (
            [0] => one
            [1] => two
        )
)

Can PHP array_merge_recursive merge more than two arrays?

Yes, array_merge_recursive can take multiple arrays at once. It merges them all recursively.
$arr1 = array("id" => 1);
$arr2 = array("id" => 2, "name" => "John");
$arr3 = array("city" => "London");

$result = array_merge_recursive($arr1, $arr2, $arr3);
print_r($result);
Output:
Array
(
    [id] => Array
        (
            [0] => 1
            [1] => 2
        )

    [name] => John
    [city] => London
)

How to fix unwanted nested arrays with array_merge_recursive?

array_merge_recursive creates nested arrays when keys match. To avoid this, use array_replace_recursive instead.
$a = array("color" => "red");
$b = array("color" => "blue");

print_r(array_merge_recursive($a, $b));
print_r(array_replace_recursive($a, $b));
Output:
array_merge_recursive:
Array
(
    [color] => Array
        (
            [0] => red
            [1] => blue
        )
)

array_replace_recursive:
Array
(
    [color] => blue
)

Similar Reads

PHP Predefined Constants Explained Simply

PHP has a number of predefined constants that give you some information about the language and its environment. You can…

PHP Strings: Types, Variables & Syntax Tips

If you start working with PHP, it won't take you that long to figure out that strings are everywhere. Besides…

PHP Anonymous Function: How It Works with Examples

The anonymous function in PHP lets you define a small task that doesn’t require a function name. Understand the Anonymous…

PHP array_map Function: How to Transform Arrays with Examples

PHP added the array_map() function to help you apply one function to each item in an array. Understand the array_map…

PHP array_fill_keys: Create Arrays with Specific Keys

The PHP array_fill_keys function helps you to build an array where each key has the same value. What is the…

OOP Interface PHP: How to Set Rules for Classes

PHP developers relied on class inheritance to share functionality before the OOP interface, but this approach had limits. It solves…

PHP mail() Function: A Complete Guide

PHP mail() is a great built-in function for sending an email directly from your script for account confirmations, password resets, or sending notifications.…

PHP filter_var: Understand How to Sanitize Input

PHP didn’t have a way to check or clean user input. Developers used scattered code—some wrote custom checks, others used…

PHP array_intersect_uassoc: How it Works with Examples

PHP array_intersect_uassoc checks two or more arrays and returns matches. It compares both the values and the keys with a…

PHP str_repeat: How it Works with Examples

PHP gives you many string tools. One of them is php str_repeat. This function repeats a texts as many times…

Previous Article

Git status Command with Examples

Next Article

How to Connect to SQL Server Step by Step

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *


Subscribe to Get Updates

Get the latest updates on Coding, Database, and Algorithms straight to your inbox.
No spam. Unsubscribe anytime.