How to Merge Two Arrays in PHP

Merging arrays is a fundamental task in PHP development. This article provides a quick and clear guide on how to combine two or more arrays in PHP using three primary methods: the array_merge() function, the spread operator (...), and the array union operator (+), explaining how they handle conflicting keys.


1. Using array_merge()

The array_merge() function is the most common way to combine arrays in PHP. It merges the elements of one or more arrays together.

$array1 = ['color' => 'red', 2, 4];
$array2 = ['a', 'b', 'color' => 'green', 'shape' => 'trapezoid', 4];

$result = array_merge($array1, $array2);
print_r($result);

Output:

Array
(
    [color] => green
    [0] => 2
    [1] => 4
    [2] => a
    [3] => b
    [shape] => trapezoid
    [4] => 4
)

2. Using the Spread Operator (...)

Introduced in PHP 7.4 (and expanded to string keys in PHP 8.1), the spread operator offers a cleaner and often faster syntax for merging arrays. It unpacks the array elements into a new array.

Its behavior regarding keys is identical to array_merge(): numeric keys are reindexed, and string keys on the right overwrite those on the left.

$array1 = ['apple', 'banana'];
$array2 = ['cherry', 'date'];

$result = [...$array1, ...$array2];
print_r($result);

Output:

Array
(
    [0] => apple
    [1] => banana
    [2] => cherry
    [3] => date
)

3. Using the Array Union Operator (+)

The + operator appends the right-hand array to the left-hand array. However, unlike array_merge(), it does not overwrite existing keys.

If a key exists in both the first and second array, the value from the first (left-hand) array will be kept, and the value from the second array will be ignored. This applies to both numeric and string keys.

$array1 = ['a' => 'apple', 'b' => 'banana'];
$array2 = ['a' => 'apricot', 'c' => 'cherry'];

$result = $array1 + $array2;
print_r($result);

Output:

Array
(
    [a] => apple
    [b] => banana
    [c] => cherry
)

Summary: Which one should you use?