Combining and adding numerical arrays in PHP
When using the array_merge() function, if the keys are numerical, then the array will be reindexed starting at 0. If you want to key the same numerical indexes, simply add the arrays together.
The + operator returns the right-hand array appended to the left-hand array; for keys that exist in both arrays, the elements from the left-hand array will be used, and the matching elements from the right-hand array will be ignored.
array_merge() has slightly different behavior:
If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended. Values in the input array with numeric keys will be renumbered with incrementing keys starting from zero in the result array.
$array1 = [1 => 'A', 2=>'B', 3=>'C']; $array1 = [5 => 'X', 6=>'Y', 2=>'Z']; $merged = array_merge($array1, $array2); //returns reindexed array [0 => 'A', 1=>'B', 2=>'C', 3=>'X', 4=>'Y', 5=>'Z'] $added = $array1 + $array2; //returns combined array with indexes intact [1 => 'A', 2=>'B', 3=>'C', 5 =>'X', 6=>'Y', 2=>'Z' ]