Skip to content
Tutorials Center
My learning

Topics

PHP Reference ยท Array Functions

PHP array_merge() function

Reference for PHP array_merge(): combine arrays into one, how string and integer keys behave, the difference from the + operator and the spread operator.

The array_merge() function combines one or more arrays into a new array. Values from later arrays are appended after earlier ones. The original arrays are not changed.

Keys are treated in two different ways. Integer keys are discarded and the values are renumbered from 0, so lists simply concatenate. String keys are kept, and when the same string key appears twice, the later value wins.

PHP
print_r(array_merge([1, 2], [3]));            // [1, 2, 3]
print_r(array_merge(["a" => 1], ["a" => 2])); // ["a" => 2]

Try it

PHP Lists and associative arrays

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

PHP array_merge() compared with + and the spread operator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Syntax

PHP
array_merge(array ...$arrays): array
Name Description
...$arrays Zero or more arrays to combine, from left to right.

Return value: a new array. With no arguments, an empty array.

Errors / Exceptions: a TypeError if any argument is not an array.

Usage notes

  • Integer keys are renumbered; string keys are overwritten by later arrays. If you need integer keys preserved, use + or array_replace().
  • + keeps the left value for equal keys, while array_merge() keeps the right one. They also differ for lists: [1, 2] + [3, 4, 5] gives [1, 2, 5].
  • Spread works too. [...$a, ...$b] behaves like array_merge($a, $b) for integer keys; string keys are supported in unpacking since PHP 8.1 and also let later values win.
  • Merging many arrays at once: array_merge(...$listOfArrays). Calling it in a loop ($all = array_merge($all, $x)) copies the result each time and is quadratic.
  • Before PHP 7.4 calling it with no arguments raised a warning; now it returns [].
  • Nested arrays are not merged deeply. The later nested value replaces the earlier one. Use array_merge_recursive() for deep merging (with its own surprises) or write a small recursive helper.
  • Numeric strings such as "5" are integer keys in PHP arrays, so they are renumbered too.