PHP
Smart Recursive Array Merge with Overwriting for Conflicts
Implement a custom PHP function to recursively merge multiple arrays, intelligently handling nested structures and overwriting scalar values from later arrays on conflict.
<?php
/**
* Recursively merges two or more arrays.
* If a key exists in both arrays, the value from the later array takes precedence.
* For associative arrays, nested arrays are merged, scalar values are overwritten.
*
* @param array $array1 The first array.
* @param array ...$arrays Additional arrays to merge.
* @return array The merged array.
*/
function smartRecursiveArrayMerge(array $array1, array ...$arrays): array
{
foreach ($arrays as $array2) {
foreach ($array2 as $key => $value) {
if (is_array($value) && isset($array1[$key]) && is_array($array1[$key])) {
$array1[$key] = smartRecursiveArrayMerge($array1[$key], $value);
} else {
$array1[$key] = $value;
}
}
}
return $array1;
}
$configDefault = [
'app_name' => 'My App',
'database' => [
'host' => 'localhost',
'port' => 3306,
'user' => 'root',
'options' => [
'strict_mode' => true
]
],
'features' => [
'logging' => true,
'analytics' => false
]
];
$configProduction = [
'database' => [
'host' => 'prod-db.example.com',
'user' => 'prod_user',
'password' => 'secure_pass',
'options' => [
'strict_mode' => false, // Overwrites default
'ssl_enabled' => true
]
],
'features' => [
'analytics' => true // Overwrites default
],
'app_env' => 'production'
];
$mergedConfig = smartRecursiveArrayMerge($configDefault, $configProduction);
print_r($mergedConfig);
/*
Output:
Array
(
[app_name] => My App
[database] => Array
(
[host] => prod-db.example.com
[port] => 3306
[user] => prod_user
[options] => Array
(
[strict_mode] =>
[ssl_enabled] => 1
)
[password] => secure_pass
)
[features] => Array
(
[logging] => 1
[analytics] => 1
)
[app_env] => production
)
*/
How it works: This `smartRecursiveArrayMerge` function provides a more flexible alternative to PHP's built-in `array_merge_recursive`. Unlike the built-in function which appends values for identical keys, this custom implementation recursively merges arrays, ensuring that scalar values from later arrays overwrite those from earlier arrays. This behavior is highly beneficial for configuration systems where default settings are overridden by environment-specific or user-defined configurations, maintaining a clean and predictable merge outcome for deeply nested structures.