PHP
Recursively Merge and Overwrite PHP Arrays
Understand how to merge multiple PHP arrays recursively, with later arrays overwriting values from earlier ones, using `array_replace_recursive()` for robust configuration management.
<?php
$defaults = [
'database' => [
'host' => 'localhost',
'port' => 3306,
'user' => 'root',
'password' => ''
],
'cache' => [
'enabled' => true,
'lifetime' => 3600
]
];
$userConfig = [
'database' => [
'host' => 'production.db',
'user' => 'produser'
],
'cache' => [
'enabled' => false
],
'logging' => [
'level' => 'warning'
]
];
$mergedConfig = array_replace_recursive($defaults, $userConfig);
echo "Merged Configuration:
";
print_r($mergedConfig);
/*
Output:
Merged Configuration:
Array
(
[database] => Array
(
[host] => production.db
[port] => 3306
[user] => produser
[password] =>
)
[cache] => Array
(
[enabled] =>
[lifetime] => 3600
)
[logging] => Array
(
[level] => warning
)
)
*/
?>
How it works: The `array_replace_recursive()` function in PHP is ideal for merging multiple arrays where values from later arrays overwrite values from earlier ones, even within nested associative arrays. This is particularly useful for managing application configurations, where you have a set of default settings and want to override specific values with user-defined or environment-specific configurations without losing any un-overridden defaults. It smartly traverses nested arrays, merging them deeply rather than just at the top level, unlike `array_merge()`.