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 array_push Function: How it Works with Examples

PHP array_push lets you add one or more values to the end of an array. It appeared to make adding…

PHP Access Modifiers: How Public, Private & Protected Work

PHP supports OOP with access modifiers to prevent unintended changes and improve security. In this article, we will cover the…

PHP fclose(): Close Access of File Manipulation

Actually, PHP has a built-in function that doesn’t get the spotlight—fclose(). It ends the file manipulation code. Let’s break down…

Understanding the PHP Operator Precedence

The PHP operator precedence refers to when doing a calculation for three or more numbers, they are calculating its values…

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…

Get Last Insert ID in PHP with MySQL PDO and MySQLi

Keeping track of the last record inserted is often important. Whether you are managing user registrations, processing orders, or handling…

PHP Array Operators: Union, Equality, Identity

PHP arrays serve as powerful tools for storing multiple values in a single variable. To manipulate arrays efficiently, PHP provides…

PHP OOP Programming: A Complete Tutorial

A complex web application needs proper organization and maintenance to keep your code structured. This is where PHP Object-Oriented Programming…

PHP array_filter: How to Filter Array Values with Examples

You can use array_filter in PHP to remove unwanted data from arrays. It works with a custom callback or default…

Mastering PHP’s Do-While Loop: Examples and Explanation

The PHP do-while loop is a type of loop that executes a block of code at least once, and then…

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.