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, 4The spread operator
The same can be written with ...:
<?php
$a = [1, 2];
$b = [3, 4];
echo implode(', ', [...$a, ...$b]);Output:
1, 2, 3, 4The + 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, 5Without 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, 3Functions used in this recipe
- array_merge — Merges one or more arrays into one.
- array_unique — Removes duplicate values from an array.