PHP 8 reference · Array Functions

PHP array_merge_recursive() Function

Merge arrays and, when string keys clash, combine their values into arrays instead of overwriting.

PHP 8 Since 4.0

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

array_merge_recursive(array ...$arrays): array

Parameters

ParameterDescription
arrays The arrays to merge.

Return value

A new merged array.

Examples

Clashing keys become arraysTry it yourself
<?php
$a = ["tags" => ["php"], "author" => "Ada"];
$b = ["tags" => ["web"], "author" => "Alan"];
print_r(array_merge_recursive($a, $b));

Output

Array
(
    [tags] => Array
        (
            [0] => php
            [1] => web
        )

    [author] => Array
        (
            [0] => Ada
            [1] => Alan
        )

)
Config merging uses array_replace_recursive()Try it yourself
<?php
$base = ["db" => ["host" => "localhost", "port" => 5432]];
$env = ["db" => ["host" => "db.internal"]];
print_r(array_replace_recursive($base, $env)); // usually what config merging needs

Output

Array
(
    [db] => Array
        (
            [host] => db.internal
            [port] => 5432
        )

)

Version history

VersionChange
PHP 4.0Added

Was this page helpful?