PHP
Deep Merge PHP Arrays with Custom Overwrite Behavior
Implement a custom recursive function in PHP to deeply merge two arrays, handling nested structures and ensuring scalar values from the second array properly overwrite those in the first.
<?php
function array_deep_merge_overwrite(array $array1, array $array2): array {
$merged = $array1;
foreach ($array2 as $key => $value) {
if (is_array($value) && isset($merged[$key]) && is_array($merged[$key])) {
// If both are arrays, recursively merge
$merged[$key] = array_deep_merge_overwrite($merged[$key], $value);
} else {
// Otherwise, overwrite or add the value
$merged[$key] = $value;
}
}
return $merged;
}
$config_default = [
'database' => [
'host' => 'localhost',
'port' => 3306,
'user' => 'root',
'password' => ''
],
'app' => [
'name' => 'My App',
'debug' => false,
'timezone' => 'UTC'
]
];
$config_production = [
'database' => [
'host' => 'prod-db.example.com',
'user' => 'prod_user',
'password' => 'secure_pass_123'
],
'app' => [
'debug' => false, // explicitly false for prod
'timezone' => 'America/New_York'
],
'cache' => ['driver' => 'redis'] // New key not in default
];
$final_config = array_deep_merge_overwrite($config_default, $config_production);
print_r($final_config);
/*
Output:
Array
(
[database] => Array
(
[host] => prod-db.example.com
[port] => 3306
[user] => prod_user
[password] => secure_pass_123
)
[app] => Array
(
[name] => My App
[debug] =>
[timezone] => America/New_York
)
[cache] => Array
(
[driver] => redis
)
)
*/
How it works: While `array_merge_recursive()` can merge arrays, it concatenates non-array values instead of overwriting them, which is often not desired for configuration or object properties. This `array_deep_merge_overwrite` function provides a custom recursive solution. It iterates through the second array, and if a key exists in both arrays and both values are arrays, it recursively merges them. Otherwise, it simply overwrites the value in the first array with the value from the second, ensuring that later values take precedence for scalars and deep merging occurs for nested arrays.