PHP 8 reference · Array Functions

PHP array_merge() Function

Merge one or more arrays into a new array. Numeric keys are renumbered; for string keys the later value wins.

PHP 8 Since 4.0

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

array_merge(array ...$arrays): array

Parameters

ParameterDescription
arrays The arrays to merge.

Return value

A new merged array.

Examples

Join listsTry it yourself
<?php
print_r(array_merge(["a", "b"], ["c"], ["d", "e"]));

Output

Array
(
    [0] => a
    [1] => b
    [2] => c
    [3] => d
    [4] => e
)
Override defaultsTry it yourself
<?php
$defaults = ["color" => "blue", "size" => "M"];
$chosen = ["size" => "L"];
print_r(array_merge($defaults, $chosen));

Output

Array
(
    [color] => blue
    [size] => L
)
array_merge() vs +Try it yourself
<?php
print_r(array_merge([5 => "a"], [5 => "b"])); // renumbered
print_r([5 => "a"] + [5 => "b"]);             // + keeps the first

Output

Array
(
    [0] => a
    [1] => b
)
Array
(
    [5] => a
)

Common mistakes

  • Integer keys are renumbered, so IDs used as keys are lost. Use $a + $b or array_replace() to keep them.
  • Merging inside a loop ($all = array_merge($all, $chunk)) is slow; collect chunks and call array_merge(...$chunks) once.

Version history

VersionChange
PHP 4.0Added
PHP 7.4Can be called with no arguments (returns []).

In other languages

Was this page helpful?