PHP
Recursively Merging Associative Arrays (e.g., Configuration Overrides)
Learn how to perform a deep, recursive merge of multiple associative arrays, perfect for overriding default configuration settings with user-defined or environment-specific values in PHP applications.
<?php
$defaultConfig = [
'database' => [
'host' => 'localhost',
'port' => 3306,
'user' => 'root',
'password' => ''
],
'app' => [
'debug' => true,
'timezone' => 'UTC'
]
];
$userConfig = [
'database' => [
'user' => 'admin',
'password' => 'secret'
],
'app' => [
'debug' => false,
'locale' => 'en_US'
]
];
$envConfig = [
'database' => [
'host' => 'production.db'
]
];
// Merge default, user, and environment configurations
$finalConfig = array_replace_recursive($defaultConfig, $userConfig, $envConfig);
echo "Final Merged Configuration:
";
print_r($finalConfig);
// Example: What if a key is entirely new in a later array?
$defaultA = ['settings' => ['theme' => 'light']];
$overrideB = ['settings' => ['color' => 'blue']];
$mergedAB = array_replace_recursive($defaultA, $overrideB);
echo "
Merging with new keys:
";
print_r($mergedAB);
?>
How it works: `array_replace_recursive()` is a crucial function for merging associative arrays, particularly when dealing with nested data structures like configuration settings. It recursively replaces values in the first array with values from subsequent arrays. Unlike `array_merge()`, which simply appends new elements or overwrites non-associative (numeric) keys, `array_replace_recursive()` will descend into nested arrays and replace only the corresponding keys. If a key exists in a later array but not an earlier one, it will be added. This behavior is ideal for scenarios where you have default settings and want to apply overrides from various sources (e.g., user preferences, environment variables) while preserving the original structure.