PHP
Deep Merge Associative Arrays Recursively with Overwrite
Implement a custom PHP function to recursively merge two associative arrays, correctly overwriting scalar values and intelligently merging nested arrays.
<?php
/**
* Recursively merges two or more arrays.
* This function intelligently merges arrays by overwriting scalar values
* and recursively merging nested arrays, unlike array_merge_recursive.
*
* @param array $array1 The initial array.
* @param array $array2 The array to merge into the first.
* @return array The merged array.
*/
function array_deep_merge(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_deep_merge($merged[$key], $value);
} else {
$merged[$key] = $value;
}
}
return $merged;
}
$configDefault = [
'database' => [
'host' => 'localhost',
'port' => 3306,
'user' => 'root',
'password' => ''
],
'app' => [
'name' => 'MyApp',
'env' => 'development'
]
];
$configCustom = [
'database' => [
'host' => 'production_db',
'password' => 'secure_pass'
],
'app' => [
'env' => 'production'
],
'new_setting' => 'value'
];
$finalConfig = array_deep_merge($configDefault, $configCustom);
print_r($finalConfig);
/* Expected Output:
Array
(
[database] => Array
(
[host] => production_db
[port] => 3306
[user] => root
[password] => secure_pass
)
[app] => Array
(
[name] => MyApp
[env] => production
)
[new_setting] => value
)
*/
?>
How it works: This snippet provides a custom `array_deep_merge` function that intelligently merges two associative arrays recursively. Unlike PHP's built-in `array_merge_recursive`, this function handles conflicts by overwriting scalar values from the second array if a key exists in both. If both values for a given key are arrays, it recursively calls itself to merge those sub-arrays, ensuring a complete and intuitive deep merge behavior, suitable for configuration overrides.