PHP
Recursively Merge Associative Arrays
Learn how to deeply merge two or more PHP associative arrays, combining nested arrays and preserving data, ideal for configuration management.
<?php
function array_merge_recursive_distinct_snippet(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] = array_merge_recursive_distinct_snippet($merged[$key], $value);
} else {
$merged[$key] = $value;
}
}
return $merged;
}
$configDefault = [
'database' => [
'host' => 'localhost',
'user' => 'root',
'pass' => '',
],
'app' => [
'name' => 'MyApp',
'debug' => true,
],
'features' => ['search', 'profile']
];
$configUser = [
'database' => [
'user' => 'admin',
'pass' => 'secret',
'port' => 3306,
],
'app' => [
'debug' => false,
'timezone' => 'UTC',
],
'features' => ['analytics']
];
$mergedConfig = array_merge_recursive_distinct_snippet($configDefault, $configUser);
// var_dump($mergedConfig);
/*
Expected $mergedConfig output:
Array (
[database] => Array (
[host] => localhost
[user] => admin
[pass] => secret
[port] => 3306
)
[app] => Array (
[name] => MyApp
[debug] =>
[timezone] => UTC
)
[features] => Array (
[0] => analytics
)
)
*/
How it works: This custom function `array_merge_recursive_distinct_snippet` provides a powerful way to merge two associative arrays deeply. It iterates through the second array (`$array2`). If a key exists in both arrays and both values are themselves arrays, it recursively merges those sub-arrays. Otherwise, if the key exists or not, the value from `$array2` overwrites the corresponding value in `$array1` (or is added if new). This is particularly useful for configuration files where you have default settings and user-specific overrides.