PHP
Recursively Merge Two PHP Arrays with Deep Merging
Implement a deep merge function for two PHP arrays, intelligently combining sub-arrays and values instead of just overwriting keys.
function arrayMergeRecursiveDistinct(array $array1, array $array2): array
{
$merged = $array1;
foreach ($array2 as $key => $value) {
if (is_array($value) && isset($merged[$key]) && is_array($merged[$key])) {
$merged[$key] = arrayMergeRecursiveDistinct($merged[$key], $value);
} else {
$merged[$key] = $value;
}
}
return $merged;
}
$arrayA = [
'config' => ['timeout' => 30, 'log_level' => 'info'],
'data' => [1, 2],
'options' => ['debug' => true],
'version' => '1.0'
];
$arrayB = [
'config' => ['timeout' => 60, 'retries' => 5],
'data' => [3, 4],
'options' => ['cache' => false],
'new_feature' => true
];
$mergedArray = arrayMergeRecursiveDistinct($arrayA, $arrayB);
/*
$mergedArray will be:
[
'config' => ['timeout' => 60, 'log_level' => 'info', 'retries' => 5],
'data' => [3, 4], // Overwritten as array data is not merged numerically by default
'options' => ['debug' => true, 'cache' => false],
'version' => '1.0',
'new_feature' => true
]
*/
How it works: This snippet provides an `arrayMergeRecursiveDistinct` function for performing a deep merge of two arrays. Unlike `array_merge` or `array_merge_recursive`, this function intelligently combines arrays: if a key exists in both arrays and its values are both arrays, it recursively merges those sub-arrays. For scalar values or when types differ, the value from the second array (`$array2`) overwrites the corresponding value from the first array (`$array1`), ensuring a comprehensive merge.