PHP
Deeply Merge Associative Arrays Recursively
Learn how to combine multiple associative arrays into a single array, recursively merging nested structures and preserving all values in PHP for configuration or settings.
<?php
function array_merge_recursive_distinct(array ...$arrays): array
{
$result = [];
foreach ($arrays as $array) {
foreach ($array as $key => $value) {
if (is_array($value) && isset($result[$key]) && is_array($result[$key])) {
$result[$key] = array_merge_recursive_distinct($result[$key], $value);
} else {
$result[$key] = $value;
}
}
}
return $result;
}
$array1 = ['config' => ['database' => 'mydb', 'host' => 'localhost'], 'settings' => ['debug' => true]];
$array2 = ['config' => ['host' => '127.0.0.1', 'port' => 3306], 'user' => 'admin'];
$merged = array_merge_recursive_distinct($array1, $array2);
print_r($merged);
/*
Output:
Array
(
[config] => Array
(
[database] => mydb
[host] => 127.0.0.1
[port] => 3306
)
[settings] => Array
(
[debug] => 1
)
[user] => admin
)
*/
How it works: This function provides a robust way to deeply merge multiple associative arrays. Unlike `array_merge_recursive`, which appends numerical keys and can create nested arrays for identical string keys, this custom function recursively overwrites existing scalar or non-array values with new ones, while deeply merging nested arrays. This is particularly useful for combining configuration files where you want later arrays to override earlier ones while preserving distinct settings within nested structures.