PHP
Recursively Merge Multiple PHP Arrays with array_merge_recursive
Understand how array_merge_recursive() in PHP combines multiple arrays, merging duplicate string keys and appending numeric keys.
<?php
$array1 = [
'data' => [
'config' => ['optionA' => true, 'optionB' => 'value1'],
'list' => [1, 2]
],
'common' => 'shared'
];
$array2 = [
'data' => [
'config' => ['optionB' => 'value2', 'optionC' => false],
'list' => [3, 4]
],
'new_item' => 'added'
];
$mergedArray = array_merge_recursive($array1, $array2);
print_r($mergedArray);
$array3 = [
'data' => [
'list' => [5, 6]
]
];
$deepMergedArray = array_merge_recursive($mergedArray, $array3);
print_r($deepMergedArray);
?>
How it works: The `array_merge_recursive()` function is designed to merge two or more arrays recursively. If a key from the second array is found in the first array, and both values are arrays, it merges them recursively. If the values are not arrays, the value from the second array overwrites the first. Numeric keys are appended, while string keys are merged, converting scalar values to arrays if duplicate string keys are found at the same level, making it ideal for configuration or multi-source data merging.