PHP
Deep Merge Arrays with Overwriting (Custom Function)
Discover how to recursively merge two or more PHP arrays, ensuring that values from later arrays overwrite existing keys from earlier arrays for deep configurations.
function array_merge_deep(array ...$arrays): array {
$result = array_shift($arrays);
foreach ($arrays as $array) {
foreach ($array as $key => $value) {
if (isset($result[$key]) && is_array($result[$key]) && is_array($value)) {
$result[$key] = array_merge_deep($result[$key], $value);
} else {
$result[$key] = $value;
}
}
}
return $result;
}
$config1 = ['database' => ['host' => 'localhost', 'user' => 'root'], 'app' => ['name' => 'MyApp']];
$config2 = ['database' => ['password' => 'pass', 'host' => '127.0.0.1'], 'app' => ['version' => '1.0']];
$config3 = ['database' => ['port' => 3306]];
$mergedConfig = array_merge_deep($config1, $config2, $config3);
print_r($mergedConfig);
/* Output:
Array
(
[database] => Array
(
[host] => 127.0.0.1
[user] => root
[password] => pass
[port] => 3306
)
[app] => Array
(
[name] => MyApp
[version] => 1.0
)
)*/
How it works: This custom `array_merge_deep` function provides a powerful way to merge multiple arrays recursively, with a critical difference from `array_merge_recursive`: it overwrites scalar values when keys conflict instead of merging them into another nested array. When two arrays have the same key and both values are themselves arrays, it recursively calls `array_merge_deep` on those sub-arrays. Otherwise, the value from the later array takes precedence, making it ideal for merging configuration files where you want later settings to override earlier ones.