PHP › Arrays in PHP
How do you merge, combine, and compare arrays in PHP, and what are the subtle differences between array_merge and the plus operator?
AdvancedAnswer
array_merge combines two or more arrays, and for string keys, later values overwrite earlier ones while numeric keys are renumbered sequentially, whereas the plus operator also combines arrays but keeps the first array's values for any keys that exist in both, including numeric keys, without any renumbering, meaning the two approaches can produce noticeably different results, especially when merging indexed arrays.
$a = [1, 2, 3];
$b = [4, 5, 6];
print_r(array_merge($a, $b));
print_r($a + $b);Real-world example A configuration system merges a set of default settings with user provided overrides using the plus operator specifically because it wants the user's values to only fill in missing keys rather than overwrite already defined ones.