PHP 8.3.0 RC 6 available for testing

array_merge

(PHP 4, PHP 5, PHP 7, PHP 8)

array_merge合并一个或多个数组

说明

array_merge(array ...$arrays): array

将一个或多个数组的单元合并起来,一个数组中的值附加在前一个数组的后面。返回作为结果的数组。

如果输入的数组中有相同的字符串键名,则该键名后面的值将覆盖前一个值。然而,如果数组包含数字键名,后面的值将 不会 覆盖原来的值,而是附加到后面。

如果输入的数组存在以数字作为索引的内容,则这项内容的键名会以连续方式重新索引。

参数

arrays

要合并的数组。

返回值

返回合并后的结果数组。如果参数为空,则返回空 array

更新日志

版本 说明
7.4.0 允许不带参数调用,之前版本至少需要一个参数。

示例

示例 #1 array_merge() 示例

<?php
$array1
= array("color" => "red", 2, 4);
$array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4);
$result = array_merge($array1, $array2);
print_r($result);
?>

以上示例会输出:

 
Array
(
    [color] => green
    [0] => 2
    [1] => 4
    [2] => a
    [3] => b
    [shape] => trapezoid
    [4] => 4
)

示例 #2 单一结构的 array_merge() 示例

<?php
$array1
= array();
$array2 = array(1 => "data");
$result = array_merge($array1, $array2);
?>

别忘了数字键名将会被重新编号!

 
Array
(
    [0] => data
)

如果你想完全保留原有数组并只想新的数组附加到后面,可以使用 + 运算符:

<?php
$array1
= array(0 => 'zero_a', 2 => 'two_a', 3 => 'three_a');
$array2 = array(1 => 'one_b', 3 => 'three_b', 4 => 'four_b');
$result = $array1 + $array2;
var_dump($result);
?>

第一个数组的键名将会被保留。在两个数组中存在相同的键名时,第一个数组中的同键名的元素将会被保留,第二个数组中的元素将会被忽略。

 
array(5) {
  [0]=>
  string(6) "zero_a"
  [2]=>
  string(5) "two_a"
  [3]=>
  string(7) "three_a"
  [1]=>
  string(5) "one_b"
  [4]=>
  string(6) "four_b"
}

示例 #3 array_merge() 合并非数组的类型

<?php
$beginning
= 'foo';
$end = array(1 => 'bar');
$result = array_merge((array)$beginning, (array)$end);
print_r($result);
?>

以上示例会输出:

 
    Array
    (
        [0] => foo
        [1] => bar
    )

参见

add a note

User Contributed Notes 8 notes

up
303
Julian Egelstaff
14 years ago
In some situations, the union operator ( + ) might be more useful to you than array_merge. The array_merge function does not preserve numeric key values. If you need to preserve the numeric keys, then using + will do that.

ie:

<?php

$array1
[0] = "zero";
$array1[1] = "one";

$array2[1] = "one";
$array2[2] = "two";
$array2[3] = "three";

$array3 = $array1 + $array2;

//This will result in::

$array3 = array(0=>"zero", 1=>"one", 2=>"two", 3=>"three");

?>

Note the implicit "array_unique" that gets applied as well. In some situations where your numeric keys matter, this behaviour could be useful, and better than array_merge.

--Julian
up
33
ChrisM
1 year ago
I wished to point out that while other comments state that the spread operator should be faster than array_merge, I have actually found the opposite to be true for normal arrays. This is the case in both PHP 7.4 as well as PHP 8.0. The difference should be negligible for most applications, but I wanted to point this out for accuracy.

Below is the code used to test, along with the results:

<?php
$before
= microtime(true);

for (
$i=0 ; $i<10000000 ; $i++) {
$array1 = ['apple','orange','banana'];
$array2 = ['carrot','lettuce','broccoli'];

$array1 = [...$array1,...$array2];
}

$after = microtime(true);
echo (
$after-$before) . " sec for spread\n";

$before = microtime(true);

for (
$i=0 ; $i<10000000 ; $i++) {
$array1 = ['apple','orange','banana'];
$array2 = ['carrot','lettuce','broccoli'];

$array1 = array_merge($array1,$array2);
}

$after = microtime(true);
echo (
$after-$before) . " sec for array_merge\n";
?>

PHP 7.4:
1.2135608196259 sec for spread
1.1402177810669 sec for array_merge

PHP 8.0:
1.1952061653137 sec for spread
1.099925994873 sec for array_merge
up
11
Andreas Hofmann
1 year ago
In addition to the text and Julian Egelstaffs comment regarding to keep the keys preserved with the + operator:
When they say "input arrays with numeric keys will be renumbered" they MEAN it. If you think you are smart and put your numbered keys into strings, this won't help. Strings which contain an integer will also be renumbered! I fell into this trap while merging two arrays with book ISBNs as keys. So let's have this example:

<?php
$test1
['24'] = 'Mary';
$test1['17'] = 'John';

$test2['67'] = 'Phil';
$test2['33'] = 'Brandon';

$result1 = array_merge($test1, $test2);
var_dump($result1);

$result2 = [...$test1, ...$test2]; // mentioned by fsb
var_dump($result2);
?>

You will get both:

array(4) {
[0]=>
string(4) "Mary"
[1]=>
string(4) "John"
[2]=>
string(4) "Phil"
[3]=>
string(7) "Brandon"
}

Use the + operator or array_replace, this will preserve - somewhat - the keys:

<?php
$result1
= array_replace($test1, $test2);
var_dump($result1);

$result2 = $test1 + $test2;
var_dump($result2);
?>

You will get both:

array(4) {
[24]=>
string(4) "Mary"
[17]=>
string(4) "John"
[67]=>
string(4) "Phil"
[33]=>
string(7) "Brandon"
}

The keys will keep the same, the order will keep the same, but with a little caveat: The keys will be converted to integers.
up
13
fsb at thefsb dot org
3 years ago
We no longer need array_merge() as of PHP 7.4.

[...$a, ...$b]

does the same as

array_merge($a, $b)

and can be faster too.

https://wiki.php.net/rfc/spread_operator_for_array#advantages_over_array_merge
up
3
JoshE
1 year ago
Not to contradict ChrisM's test, but I ran their code example and I got very different results for PHP 8.0.

Testing PHP 8.0.14
1.4955070018768 sec for spread
4.4120140075684 sec for array_merge
up
-1
Hayley Watson
7 months ago
Using the spread operator with array_merge allows merging any number of arrays together in one operation:

<?php
array_merge
(...$array_of_arrays);
?>

Perhaps $array_of_arrays was built up in a loop, with $array_of_arrays[] = $another_array inside the loop. Collecting the arrays together this way and then merging them all at once is many times faster than repeatedly merging arrays two at a time (doing array_merge inside the loop).
up
-1
gwyneth dot llewelyn at gwynethllewelyn dot net
3 months ago
If you're trying to merge an array with something that evaluates to NULL, you'll get unpredictable results:

<?php
$a
= ['1', '2', '4'];
$b = null;

var_dump($a);
var_dump($b);

$c = array_merge($a, $b); // this won't work
echo "The merged array is:";
var_dump($c);
?>

Depending on your error setting, you might not even get anything at all.

Under PHP 7.4:

array(3) {
[0]=>
string(1) "1"
[1]=>
string(1) "2"
[2]=>
string(1) "4"
}
NULL
PHP Warning: array_merge(): Expected parameter 2 to be an array, null given in /home/gwyneth/stupid-test.php on line 8
The merged array is: NULL

Under PHP 8.{0,1,2}:

array(3) {
[0]=>
string(1) "1"
[1]=>
string(1) "2"
[2]=>
string(1) "4"
}
NULL
PHP Fatal error: Uncaught TypeError: array_merge(): Argument #2 must be of type array, null given in /home/gwyneth/stupid-test.php:8
Stack trace:
#0 /home/gwyneth/stupid-test.php(8): array_merge()
#1 {main}
thrown in /home/gwyneth/stupid-test.php on line 8

Depending on your display/debug settings, you might not even get anything.

The solution, of course, is to do a quick & dirty test before passing the 2nd argument:

<?php
$a
= ['1', '2', '4'];
$b = null;

var_dump($a);
var_dump($b);

$c = array_merge($a, $b ?? []);
echo
"The merged array is:";
var_dump($c);
?>

Which gives the expected result (PHP 7.4 to PHP 8.2):

array(3) {
[0]=>
string(1) "1"
[1]=>
string(1) "2"
[2]=>
string(1) "4"
}
NULL
The merged array is:array(3) {
[0]=>
string(1) "1"
[1]=>
string(1) "2"
[2]=>
string(1) "4"
}

While it's perfectly legitimate to merge empty arrays, null is *not* an empty array!
up
-6
php at k dot ull dot at
1 year ago
Merge two arrays and retain only unique values.
Append values from second array.
Do not care about keys.

$array1 = [
0 => 'apple',
1 => 'orange',
2 => 'pear',
];

$array2 = [
0 => 'melon',
1 => 'orange',
2 => 'banana',
];

$result = array_keys(
array_flip($array1) + array_flip($array2)
);

Result:
[
[0] => "apple",
[1] => "orange",
[2] => "pear",
[3] => "melon",
[4] => "banana",
}
To Top