PHP
Recursively Deep Merge Associative Arrays
Master the technique of deeply merging multiple associative arrays, combining nested values intelligently by overwriting scalars and merging nested arrays.
<?php
function arrayDeepMerge(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] = arrayDeepMerge($merged[$key], $value);
} else {
$merged[$key] = $value;
}
}
return $merged;
}
$config1 = [
'database' => [
'host' => 'localhost',
'port' => 3306,
'user' => 'root'
],
'app' => [
'name' => 'MyApp',
'debug' => true
],
'api_key' => 'old_key'
];
$config2 = [
'database' => [
'port' => 3307, // Overwrites 3306
'password' => 'new_pass' // Adds new key
],
'app' => [
'env' => 'production', // Adds new key
'debug' => false // Overwrites true
],
'cache' => [
'enabled' => true
],
'api_key' => 'new_key' // Overwrites old_key
];
$finalConfig = arrayDeepMerge($config1, $config2);
/*
$finalConfig will be:
[
'database' => [
'host' => 'localhost',
'port' => 3307,
'user' => 'root',
'password' => 'new_pass'
],
'app' => [
'name' => 'MyApp',
'debug' => false,
'env' => 'production'
],
'api_key' => 'new_key',
'cache' => [
'enabled' => true
]
]
*/
How it works: This recursive `arrayDeepMerge` function combines two associative arrays. When a key exists in both arrays and its values are both arrays, it recursively merges them. If a key exists in both but values are not both arrays, or if the key only exists in the second array, the value from the second array `$array2` overwrites the first array's value. This is ideal for merging configuration settings where newer values should take precedence over old ones.