array_merge

(PHP 4, PHP 5)

array_mergeСливает один или большее количество массивов

Описание

array array_merge ( array $array1 [, array $... ] )

Сливает элементы одного или большего количества массивов таким образом, что значения одного массива присоединяются к концу предыдущего. Результатом работы функции является новый массив.

Если входные массивы имеют одинаковые строковые ключи, тогда каждое последующее значение будет заменять предыдущее. Однако, если массивы имеют одинаковые числовые ключи, значение, упомянутое последним, не заменит исходное значение, а будет добавлено в конец массива.

В результирующем массиве значения исходного массива с числовыми ключами будут перенумерованы в возрастающем порядке, начиная с нуля.

Список параметров

array1

Исходный сливаемый массив.

...

Дополнительные сливаемые массивы.

Возвращаемые значения

Возвращает результирующий массив.

Список изменений

Версия Описание
5.0.0
Внимание

Поведение функции array_merge() было изменено в PHP 5. В отличие от PHP 4, array_merge() принимает параметры только типа array. Однако вы можете использовать приведение типов. Смотрите следующий пример для уточнения подробностей.

Пример #1 Пример использования array_merge() в PHP 5

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

Результат выполнения данного примера:

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

Примеры

Пример #2 Пример использования array_merge()

<?php
$array1 
= array("color" => "red"24);
$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
)

Пример #3 Простой пример использования array_merge()

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

Помните, что числовые ключи будут перенумерованы!

Array
(
    [0] => data
)

Если вы хотите дополнить первый массив элементами второго без перезаписи элементов первого массива и без переиндексации, используйте оператор объединения массивов +:

<?php
$array1 
= array(=> 'zero_a'=> 'two_a'=> 'three_a');
$array2 = array(=> 'one_b'=> 'three_b'=> '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"
}

Смотрите также

  • array_merge_recursive() - Рекурсивное слияние двух или более массивов
  • array_combine() - Создает новый массив, используя один массив в качестве ключей, а другой в качестве соответствующих значений
  • array operators

Коментарии

Автор:
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
2009-07-31 02:48:54
http://php5.kiev.ua/manual/ru/function.array-merge.html
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
2020-03-12 13:36:52
http://php5.kiev.ua/manual/ru/function.array-merge.html
Автор:
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.
2021-11-21 04:59:48
http://php5.kiev.ua/manual/ru/function.array-merge.html
Автор:
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=$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=$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
2021-12-16 11:04:36
http://php5.kiev.ua/manual/ru/function.array-merge.html
Автор:
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
2022-03-16 00:11:57
http://php5.kiev.ua/manual/ru/function.array-merge.html

    Поддержать сайт на родительском проекте КГБ