Coding Triumph

Helpful code snippets & tutorials

How to merge two arrays in PHP

When it comes to merging two arrays (indexed or associative) in PHP, there are two methods you use in PHP: the spread syntax (also known as splat operator) or the array_merge() function. The following examples will help you understand better.

Prerequisite:

1. The spread syntax requires PHP 7.4 or higher
2. The array_merge() function requires PHP 4 or higher

1. Using the array_merge() function:

The array_merge() function will merge two arrays and generates a new one.

Code:
 $array1 = ['a', 'b', 'c'];
 $array2 = ['d', 'e', 'f', 'g', 'h'];
 
 $merged = array_merge($array1, $array2);
 print_r($merged);
Output:
Array ( 
    [0] => a
    [1] => b 
    [2] => c 
    [3] => d 
    [4] => e 
    [5] => f 
    [6] => g 
    [7] => h 
)

2. Using the spread() syntax:

The spread syntax will also combine two arrays and generates a new one.

Code:
$array1 = ['a', 'b', 'c'];
$array2 = ['d', 'e', 'f', 'g', 'h'];
 
$merged = [...$array1, ...$array2];
print_r($merged);
Output:
Array ( 
    [0] => a
    [1] => b 
    [2] => c 
    [3] => d 
    [4] => e 
    [5] => f 
    [6] => g 
    [7] => h 
)

3. The case of associative arrays that share some keys:

Although we can use array_merge() and the spread operator to combine both indexed and associative arrays, there is one minor detail we need to pay attention to in the case of associative arrays: If the input arrays have the same string keys, the later value for that key will overwrite the previous one. Let’s demonstrate that with the array_merge() function:

Code:
$array1 = ['a' => 1, 'b' => 2, 'c' => 3];
$array2 = ['c'=>'10', 'd' => 4, 'e' => 5, 'f' => 6];
$merged = array_merge($array1, $array2);
print_r($array2);
Output:
Array ( 
    [a] => 1 
    [b] => 2 
    [c] => 10 
    [d] => 4 
    [e] => 5 
    [f] => 6 
)

As you can see from the output, the value of the ‘c’ is overridden and set to ’10’.

Conclusion:

Both methods work practically the same, it only comes to the programmer’s preferences to choose one over the other.

If you like this post, please share
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments