Deep Merging Two Associative Arrays Recursively
Owner: SnippetBot
Created: 2026-07-23 00:00:29
Size: 1.47 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
/**
* Recursively merges two associative arrays. Unlike array_merge_recursive, this function
* overwrites existing scalar values and merges sub-arrays, rather than appending numeric keys.
*
* @param array $array1 The base array.
* @param array $array2 The array to merge into the base array.
* @return array The merged array.
*/
function array_merge_recursive_distinct(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($merged[$key], $value);
} else {
$merged[$key] = $value;
}
}
return $merged;
}
$config1 = [
'database' => [
'host' => 'localhost',
'port' => 3306,
'user' => 'root'
],
'settings' => [
'debug' => true,
'locale' => 'en'
],
'features' => ['A', 'B']
];
$config2 = [
'database' => [
'port' => 5432, // Overwrites port
'password' => 'secret'
],
'settings' => [
'locale' => 'es', // Overwrites locale
'timezone' => 'UTC'
],
'new_feature' => true,
'features' => ['C'] // Overwrites 'features' completely
];
$mergedConfig = array_merge_recursive_distinct($config1, $config2);
echo "Original Config 1:
";
print_r($config1);
echo "
Original Config 2:
";
print_r($config2);
echo "
Merged Config (distinct):
";
print_r($mergedConfig);