PHP
Recursively Deep Merge Multiple Associative Arrays
Learn to combine several associative arrays, merging nested arrays and overwriting scalar values in a controlled manner. Ideal for configuration or data merging.
function array_deep_merge(...$arrays): array
{
$result = [];
foreach ($arrays as $array) {
foreach ($array as $key => $value) {
if (isset($result[$key]) && is_array($result[$key]) && is_array($value)) {
$result[$key] = array_deep_merge($result[$key], $value);
} else {
$result[$key] = $value;
}
}
}
return $result;
}
$config1 = [
'database' => [
'host' => 'localhost',
'port' => 3306,
],
'debug' => true,
'modules' => ['auth', 'log'],
];
$config2 = [
'database' => [
'port' => 3307,
'user' => 'root',
],
'debug' => false,
'modules' => ['cache'],
'logging' => ['level' => 'info'],
];
$mergedConfig = array_deep_merge($config1, $config2);
print_r($mergedConfig);
How it works: The `array_deep_merge` function allows you to combine an arbitrary number of associative arrays recursively. Unlike `array_merge_recursive`, this implementation intelligently merges nested arrays by calling itself on the corresponding sub-arrays, while scalar values are overwritten by subsequent arrays. This is particularly useful for combining configuration files or applying default settings, where you want deeper structures to be merged but individual settings to be overridden.