PHP
Deep Merging Recursive Associative Arrays
Learn how to robustly merge deeply nested PHP associative arrays, ensuring later values override earlier ones for configuration or data structures, handling recursion properly.
<?php
function array_merge_recursive_distinct(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] = array_merge_recursive_distinct($merged[$key], $value);
} else {
$merged[$key] = $value;
}
}
return $merged;
}
$baseConfig = [
'database' => [
'host' => 'localhost',
'port' => 3306,
'user' => 'root',
],
'app' => [
'name' => 'MyApp',
'debug' => true,
],
'features' => ['search', 'notifications'],
];
$userConfig = [
'database' => [
'host' => 'remote.db',
'password' => 'secret',
],
'app' => [
'debug' => false,
'env' => 'production',
],
'features' => ['analytics'],
'new_setting' => 'value',
];
$finalConfig = array_merge_recursive_distinct($baseConfig, $userConfig);
// var_dump($finalConfig);
/* Expected $finalConfig (simplified):
[
'database' => [
'host' => 'remote.db',
'port' => 3306,
'user' => 'root',
'password' => 'secret',
],
'app' => [
'name' => 'MyApp',
'debug' => false,
'env' => 'production',
],
'features' => ['analytics'],
'new_setting' => 'value',
]
*/
How it works: This function `array_merge_recursive_distinct` provides a robust way to deeply merge two associative arrays. Unlike PHP's native `array_merge_recursive`, which appends values for non-associative (numeric) keys, this custom function ensures that values from the second array (`$array2`) always override corresponding values in the first array (`$array1`) for matching keys. If a key exists in both arrays and both values are arrays, it recursively calls itself to merge those nested arrays. This is crucial for managing configurations where later settings should entirely replace or extend earlier ones.