PHP
Deeply Merge Multiple PHP Arrays Recursively
Combine an arbitrary number of PHP arrays deeply and recursively, merging values for common keys rather than simply overwriting, ideal for configuration management.
<?php
function array_merge_recursive_distinct(array ...$arrays): array {
$base = array_shift($arrays);
if (!is_array($base)) {
return $base;
}
foreach ($arrays as $array) {
if (!is_array($array)) {
continue;
}
foreach ($array as $key => $value) {
if (is_array($value) && isset($base[$key]) && is_array($base[$key])) {
$base[$key] = array_merge_recursive_distinct($base[$key], $value);
} else {
$base[$key] = $value;
}
}
}
return $base;
}
$arr1 = ['a' => 1, 'b' => ['x' => 10, 'y' => 20]];
$arr2 = ['b' => ['y' => 25, 'z' => 30], 'c' => 3];
$arr3 = ['a' => 5, 'b' => ['x' => 15]];
$mergedArray = array_merge_recursive_distinct($arr1, $arr2, $arr3);
print_r($mergedArray);
/* Output:
Array
(
[a] => 5
[b] => Array
(
[x] => 15
[y] => 25
[z] => 30
)
[c] => 3
)*/
?>
How it works: This snippet provides a custom recursive function `array_merge_recursive_distinct` designed to deeply merge multiple arrays. Unlike `array_merge_recursive`, this function handles merging sub-arrays by calling itself recursively, but for scalar values (or when one of the values isn't an array), it overwrites the existing value with the new one. This behavior is often preferred for merging configuration arrays or similar structures.