Content · Programming · PHP

PHP array_merge_recursive() Function: Usage and Examples

Learn how PHP array_merge_recursive() combines nested arrays, handles duplicate keys, and differs from array_merge() and array_replace_recursive(), with practical examples.

2 views Published Oct 16, 2026 Updated Oct 16, 2026 Admin

Sometimes you need to combine PHP arrays that contain other arrays. For example, you might want to bring together course lists, application settings, or data from multiple sources.

The array_merge_recursive() function combines arrays at multiple levels. Unlike array_merge(), it collects values that share the same string key instead of simply replacing earlier values.

In this guide, you'll learn how recursive merging works, what happens with duplicate keys, and when to choose a different merging function.

What Is array_merge_recursive() in PHP?

The array_merge_recursive() function merges one or more arrays, including nested arrays.

Its syntax is:

array_merge_recursive(array ...$arrays): array

You can supply multiple arrays as arguments. The function returns a new array without modifying the original arrays.

Its behavior depends on the keys:

  • Numeric keys: Elements are appended and assigned new sequential integer keys.
  • Duplicate string keys: Their values are combined into arrays rather than overwritten.
  • Nested arrays: Matching string-keyed entries are merged recursively.

Example 1: Merging Duplicate String Keys

Let's combine two arrays containing programming language preferences.

<?php

$first = [
    "language" => "PHP",
    "level" => "Beginner"
];

$second = [
    "language" => "Python",
    "editor" => "VS Code"
];

$result = array_merge_recursive($first, $second);

print_r($result);

Output:

Array
(
    [language] => Array
        (
            [0] => PHP
            [1] => Python
        )

    [level] => Beginner
    [editor] => VS Code
)

Both arrays contain the string key language. Instead of overwriting PHP with Python, PHP stores both values in an array.

Keys that appear in only one input array keep their original values.

Example 2: Merging Nested Arrays

The main advantage of array_merge_recursive() is its ability to combine values inside nested arrays.

<?php

$first = [
    "courses" => [
        "programming" => ["PHP", "Python"]
    ]
];

$second = [
    "courses" => [
        "programming" => ["JavaScript"],
        "cloud" => ["AWS"]
    ]
];

$result = array_merge_recursive($first, $second);

print_r($result);

Output:

Array
(
    [courses] => Array
        (
            [programming] => Array
                (
                    [0] => PHP
                    [1] => Python
                    [2] => JavaScript
                )

            [cloud] => Array
                (
                    [0] => AWS
                )
        )
)

The function finds matching courses and programming keys, then combines their contents.

The cloud category is added because it doesn't exist in the first array.

How Are Numeric Keys Handled?

Numeric keys are not preserved when arrays are merged. Their values are appended and reindexed.

<?php

$first = [5 => "PHP"];
$second = [5 => "Python"];

print_r(array_merge_recursive($first, $second));

Output:

Array
(
    [0] => PHP
    [1] => Python
)

Even though both entries originally used key 5, neither value is lost.

This differs from duplicate string keys, which cause values to be grouped under the same key.

Practical Example: Combining Course Catalogs

Imagine an online learning platform receives course lists from two departments. Each department organizes its courses into categories.

We want to create a combined catalog while keeping courses grouped under their categories.

Create a file named merge-catalogs.php:

<?php

declare(strict_types=1);

// Courses from the first department.

$catalogA = [
    "programming" => [
        "PHP Basics",
        "PHP Arrays"
    ],
    "cloud" => [
        "Cloud Fundamentals"
    ]
];

// Courses from the second department.

$catalogB = [
    "programming" => [
        "Python Basics"
    ],
    "devops" => [
        "Docker Basics"
    ]
];

// Merge course catalogs.

$catalog = array_merge_recursive(
    $catalogA,
    $catalogB
);

// Display the combined catalog.

echo "<h2>Course Catalog</h2>";

foreach ($catalog as $category => $courses) {

    echo "<h3>" . htmlspecialchars(
        ucfirst($category),
        ENT_QUOTES,
        "UTF-8"
    ) . "</h3>";

    echo "<ul>";

    foreach ($courses as $course) {

        echo "<li>" . htmlspecialchars(
            $course,
            ENT_QUOTES,
            "UTF-8"
        ) . "</li>";
    }

    echo "</ul>";
}

Browser output:

Course Catalog

Programming
- PHP Basics
- PHP Arrays
- Python Basics

Cloud
- Cloud Fundamentals

Devops
- Docker Basics

The two programming lists are combined, while the Cloud and DevOps categories remain available.

This approach works well when your goal is to collect data from multiple sources rather than replace existing entries.

Note that the function doesn't remove duplicate course names. Use additional logic if every course must appear only once.

array_merge_recursive() vs array_merge() vs array_replace_recursive()

These functions handle overlapping string keys differently.

Function Duplicate String Keys
array_merge() Later values replace earlier values, including nested arrays.
array_merge_recursive() Values are combined into arrays, recursively.
array_replace_recursive() Later values replace earlier values, including corresponding nested entries.

For example, consider two configuration arrays:

<?php

$defaults = [
    "database" => [
        "host" => "localhost",
        "port" => 3306
    ]
];

$custom = [
    "database" => [
        "port" => 3307
    ]
];

$merged = array_merge_recursive(
    $defaults,
    $custom
);

print_r($merged["database"]);

Output:

Array
(
    [host] => localhost
    [port] => Array
        (
            [0] => 3306
            [1] => 3307
        )
)

The port setting becomes an array containing both values. This may be undesirable when the application expects a single integer.

If you want the custom port to replace the default while preserving the host setting, use array_replace_recursive() instead.

Common Mistakes

  • Expecting later values to overwrite earlier ones: Duplicate string-keyed values are combined, not replaced.
  • Assuming numeric keys are preserved: Numeric elements are appended and reindexed.
  • Expecting duplicate values to disappear: The function does not automatically remove duplicates.
  • Using it for configuration overrides: Consider array_replace_recursive() when settings should have one final value.
  • Assuming output types remain unchanged: A string or integer may become an array when duplicate string keys are merged.

Key Takeaways

  • array_merge_recursive() combines arrays at multiple levels.
  • Duplicate string keys cause values to be collected into arrays.
  • Nested arrays are merged recursively.
  • Numeric-keyed elements are appended and reindexed.
  • Original arrays remain unchanged.
  • Use array_replace_recursive() when nested values should be overwritten instead.

The array_merge_recursive() function is useful for combining nested collections while retaining values from multiple sources. Understanding its treatment of duplicate keys is essential for avoiding unexpected array structures.

For additional details, see the official PHP array_merge_recursive() documentation.

Share this resourceSend this page to someone who may find it useful.