Merging arrays
If you need to merge two or more arrays you can choose to use the array_merge()
function or use the spread operator.
Merge arrays with array_merge()
The array_merge()
function merges or appends 2 or more arrays.
If you have 2 arrays, the first one with 3 elements and the second one with 4 elements, array_merge()
will return a new array with 7 elements.
The result is an array with 7 elements with keys that start from 0:
Very simple. Now letβs focus on the keys. In PHP, arrays are implemented as maps, a kind of list that associates values to keys.
Key collision: array merge of arrays with numeric keys
If the keys are integers during the merge operation the keys are βrewrittenβ, so you will obtain an array with keys starting from 0, and the original keys donβt matter. Consider the following example for clarity:
The result is an array with 7 elements with new keys:
Key collision: array merge of arrays with string keys
If the keys are strings the merge operation keeps the original keys. In case of collision, only the last element will be included in the array:
Take a look at what happens to the (βthreeβ => 3) element of the first array and the (βthreeβ => βthreeβ) element of the second array. Because of the βcollisionβ (βthreeβ was used as a key twice), only the value associated with the last βthreeβ is preserved:
Merge arrays with the spread operator
The spread operator ...
used with arrays, expands the items of the array.
Merging arrays via the spread operator (...
) involves combining two or more arrays into a single array by unpacking their elements. The unpacked elements of each array will be the elements of the new array, like the next example:
In the example above the $items
array is a flat array with all the elements from the $array_1
and $array_2
arrays.
Using the spread operator, regarding the collision of keys, the same explanation made for the array_merge()
function applies.