Merging an array with the + operator vs array_merge

Published Mar 10, 2018Last updated Mar 13, 2018

For performance reason, you would like to merge an array with the operator +.
After performing your instruction, you arrive at a result that you didn't expect.
For example, let's say we want to merge with the + operator these arrays below.

$array1 = [1,2,3];
$array2 = [4,5,6,7,8,9];
$array3 = $array1+$array2;
print_r($array3);
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 7
    [4] => 8
    [5] => 9
)

The first time I did this, I was expecting to have [1,2,3,4,5,6,7,8,9] as a result.
As you can see above, the output combine the length of the first array variable then use that to begin the length of the second array.

Let's apply the same behavior with the native function array_merge and see what would happen.

$array1 = [1,2,3];
$array2 = [4,5,6,7,8,9];

$array3 = array_merge($array1,$array2);

print_r($array3);
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [5] => 6
    [6] => 7
    [7] => 8
    [8] => 9
)

The output is entirely different, by using array_merge we have both the content of the first array and the second altogether.

The lesson we can learn here is that, if you already know the value of the first array with its indexes along with the value of the second array with the same indexes then why not using the + operator to gain performance, especially in a context in which you have to merge a lot of data.

Otherwise, you can use the native function array_merge which is more predictable.

Discover and read more posts from Bart ehui
get started