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
Syntax
array_merge_recursive(array ...$arrays): array
Parameters
| Parameter | Description |
|---|---|
arrays |
The arrays to merge. |
Return value
A new merged array.
Examples
<?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
)
)<?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
| Version | Change |
|---|---|
| PHP 4.0 | Added |
Related
array_merge()· Merge one or more arrays into a new array. Numeric keys are renumbered; for string keys the later value wins.array_replace()· Replace values of the first array with values that have the same keys in later arrays. Numeric keys are kept.- PHP Arrays · tutorial
- PHP Array Functions · tutorial