What does array_merge() do?
array_merge() appends the elements of each array to the previous one. Numeric keys are renumbered from 0, while string keys from later arrays overwrite earlier ones. This makes it handy for merging configuration defaults with user options.
Syntax
array_merge(array ...$arrays): array
Parameters
...$arrays- Any number of arrays to merge, in order. Since PHP 7.4 it can be called with no arguments and returns an empty array.
Return value
The merged array.
array_merge() examples
Every example below shows the exact output it produces. Paste any of them into the editor above (or the online compiler) to run it.
1. Merge indexed arrays
<?php
$a = [1, 2, 3];
$b = [4, 5];
print_r(array_merge($a, $b));
Output:
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
)
2. String keys overwrite, numeric keys are renumbered
<?php
$defaults = ["color" => "blue", "size" => "M", 5 => "five"];
$options = ["size" => "L", 5 => "FIVE"];
print_r(array_merge($defaults, $options));
Output:
Array
(
[color] => blue
[size] => L
[0] => five
[1] => FIVE
)
3. array_merge() vs the + operator vs spread (PHP 8.1+)
<?php
$a = ["x" => 1, 0 => "a"];
$b = ["x" => 2, 0 => "b", 1 => "c"];
print_r($a + $b);
print_r(array_merge($a, $b));
print_r([...$a, ...$b]);
Output:
Array
(
[x] => 1
[0] => a
[1] => c
)
Array
(
[x] => 2
[0] => a
[1] => b
[2] => c
)
Array
(
[x] => 2
[0] => a
[1] => b
[2] => c
)
4. Flatten a list of arrays
<?php
$chunks = [[1, 2], [3], [4, 5]];
echo implode(", ", array_merge(...$chunks)) . "\n";
print_r(array_merge());
Output:
1, 2, 3, 4, 5 Array ( )
Common mistakes and gotchas
- Lost numeric keys: IDs used as keys (e.g.
[42 => "Ann"]) are renumbered. Use$a + $borarray_replace()to keep them. - + keeps the first value: with the union operator, keys already in the left array win; with
array_merge(), the right array wins for string keys. - Merging in a loop:
$all = array_merge($all, $chunk)inside a loop copies the array each time. Collect chunks and callarray_merge(...$chunks)once. - Nested arrays:
array_merge()is shallow; usearray_merge_recursive()orarray_replace_recursive()for deep merges.