Combining and adding numerical arrays in PHP cover image

Combining and adding numerical arrays in PHP

Sam Ciaramilaro • April 10, 2015

Snippets

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.

http://php.net/manual/en/language.operators.array.php

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.

http://php.net/manual/en/function.array-merge.php

Example:

// When using the array_merge() function, if the keys are numerical, then the array will be reindexed starting at 0.
// If you want to keep 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.

$array1 = [1 => 'A', 2 => 'B', 3 => 'C'];
$array2 = [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']