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
Syntax
array_merge(array ...$arrays): array
Parameters
| Parameter | Description |
|---|---|
arrays |
The arrays to merge. |
Return value
A new merged array.
Examples
<?php
print_r(array_merge(["a", "b"], ["c"], ["d", "e"]));
Output
Array
(
[0] => a
[1] => b
[2] => c
[3] => d
[4] => e
)<?php
$defaults = ["color" => "blue", "size" => "M"];
$chosen = ["size" => "L"];
print_r(array_merge($defaults, $chosen));
Output
Array
(
[color] => blue
[size] => L
)<?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 + $borarray_replace()to keep them. - Merging inside a loop (
$all = array_merge($all, $chunk)) is slow; collect chunks and callarray_merge(...$chunks)once.
Version history
In other languages
list.extend()· Pythondict.update()· Pythonarray.concat()· JavaScriptObject.assign()· JavaScript
Related
array_merge_recursive()· Merge arrays and, when string keys clash, combine their values into arrays instead of overwriting.array_replace()· Replace values of the first array with values that have the same keys in later arrays. Numeric keys are kept.array_combine()· Create an array by using one array for keys and another for values. Both arrays must have the same number of elements.array_push()· Add one or more elements to the end of an array and return its new length. $array[] = $value does the same for one value.- PHP Arrays · tutorial
- PHP Array Functions · tutorial