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 filter_var_array: How to Validate Multiple Inputs

The filter_var_array() appeared to make input validation simple and sanitization in PHP. It handles multiple inputs with different filters was…

PHP Bitwise Operators: AND, OR, XOR, NOT with Examples

Bitwise operators use symbols like &, |, and ^, and they work at the binary level. But once you understand…

PHP List MongoDB Collections

Sometimes, you may need to list collections with MongoDB in a PHP environment to manage or analyze your database structure.…

PHP array_intersect Function: How it Works with Examples

The PHP array_intersect function finds common values in arrays and returns matches as a new array. Understand the array_intersect in…

PHP array_intersect_assoc: How it Works with Examples

PHP array_intersect_assoc compares values and keys in arrays. It returns matches with the same key and value from all arrays…

PHP Hello World: Write Your First Program with Code Example

You always start with “Hello World” when you learn a new language. It keeps things simple. You see right away…

PHP mb_strtolower: How to Handle Multibyte Strings Properly

The mb_strtolower() function in PHP turns every letter in a string into lowercase. It works with multibyte encodings like UTF-8.…

PHP While Loop: Iterating Through Code Blocks

The PHP “while” loop is a simple tool that repeatedly runs a block of code as long as a certain…

PHP $_POST: Handling Form Data in PHP

The term $_POST is quite familiar territory when one works with forms in PHP. This tutorial talks about what $_POST does, how to use…

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…

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.