Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to merge two arrays

Short answer

array_merge() joins arrays into one:

<?php
 
echo implode(', ', array_merge([1, 2], [3, 4]));

Output:

1, 2, 3, 4

The spread operator

The same can be written with ...:

<?php
 
$a = [1, 2];
$b = [3, 4];
 
echo implode(', ', [...$a, ...$b]);

Output:

1, 2, 3, 4

The + operator

The + operator keeps keys and does not overwrite existing ones, so it does not suit plain lists:

<?php
 
echo implode(', ', [1, 2] + [3, 4, 5]);

Output:

1, 2, 5

Without duplicates

To avoid repeated values in the result, add array_unique():

<?php
 
echo implode(', ', array_values(array_unique(array_merge([1, 2], [2, 3]))));

Output:

1, 2, 3

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.