PHP
Recursively Merge Multiple Arrays
Combine multiple PHP arrays, including nested arrays, into a single array, prioritizing values from later arrays for common keys, useful for configuration.
function array_merge_recursive_distinct(array ...$arrays): array {
$merged = [];
foreach ($arrays as $array) {
foreach ($array as $key => $value) {
if (is_array($value) && isset($merged[$key]) && is_array($merged[$key])) {
$merged[$key] = array_merge_recursive_distinct($merged[$key], $value);
} else {
$merged[$key] = $value;
}
}
}
return $merged;
}
$config1 = [
'app_name' => 'MyApp',
'database' => [
'host' => 'localhost',
'port' => 3306,
],
'features' => ['auth', 'logging'],
];
$config2 = [
'database' => [
'port' => 3307,
'user' => 'admin',
],
'features' => ['auth', 'payments'],
'debug_mode' => true,
];
$mergedConfig = array_merge_recursive_distinct($config1, $config2);
// print_r($mergedConfig);
/*
Output:
Array
(
[app_name] => MyApp
[database] => Array
(
[host] => localhost
[port] => 3307
[user] => admin
)
[features] => Array
(
[0] => auth
[1] => payments
)
[debug_mode] => 1
)
*/
How it works: This custom function `array_merge_recursive_distinct` provides a more intuitive deep merge for arrays compared to PHP's native `array_merge_recursive`. It iterates through multiple input arrays. When encountering a key that exists in both the current merged array and the array being processed, if both values are arrays, it recursively merges them. Otherwise, it simply overwrites the existing value with the new one, ensuring that later arrays take precedence for scalar values. This is particularly useful for merging configuration files.