PHP
Custom Recursive Array Merge with Conflict Resolution
Implement a robust PHP function for recursively merging multiple arrays, offering flexible strategies to resolve value conflicts, such as summing numbers, concatenating strings, or prioritizing values.
<?php
function customRecursiveArrayMerge(array ...$arrays): array
{
$merged = [];
foreach ($arrays as $array) {
foreach ($array as $key => $value) {
if (isset($merged[$key]) && is_array($value) && is_array($merged[$key])) {
// Both are arrays, recurse
$merged[$key] = customRecursiveArrayMerge($merged[$key], $value);
} elseif (isset($merged[$key]) && is_numeric($value) && is_numeric($merged[$key])) {
// Both are numeric, sum them
$merged[$key] += $value;
} elseif (isset($merged[$key]) && is_string($value) && is_string($merged[$key])) {
// Both are strings, concatenate them (with a separator)
$merged[$key] .= ', ' . $value;
} else {
// For other types or conflicts, the last value wins
$merged[$key] = $value;
}
}
}
return $merged;
}
$arr1 = ['a' => 1, 'b' => 'hello', 'c' => ['x' => 10, 'y' => 20], 'd' => 5];
$arr2 = ['a' => 2, 'b' => ' world', 'c' => ['x' => 5, 'z' => 30], 'd' => 10, 'e' => 'new'];
$arr3 = ['a' => 3, 'c' => ['y' => 25, 'w' => 40]];
$mergedArray = customRecursiveArrayMerge($arr1, $arr2, $arr3);
/*
Example Output:
[
"a" => 6, // 1 + 2 + 3
"b" => "hello, world", // "hello" . ", " . " world"
"c" => [
"x" => 15, // 10 + 5
"y" => 45, // 20 + 25
"z" => 30,
"w" => 40
],
"d" => 15, // 5 + 10
"e" => "new"
]
*/
How it works: This snippet provides a highly customizable `customRecursiveArrayMerge` function. Unlike `array_merge_recursive`, it offers defined conflict resolution. It can recursively merge nested arrays, sum numeric values, concatenate strings (with a separator), and overwrite other conflicting values, providing fine-grained control over how merged data behaves.