Перейти к содержимому

Php как объединить два массива

  • автор:

array_merge

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

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

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

array_merge

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

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

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

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

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

Возвращает результирующий массив. Если вызывается без аргументов, возвращает пустой массив ( array ).

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

Версия Описание
7.4.0 Функция теперь может быть вызвана без каких-либо параметров. Ранее требовался хотя бы один параметр.

Примеры

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

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

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

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

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

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

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

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

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

  • array_merge_recursive() — Рекурсивное слияние одного или более массивов
  • array_replace() — Заменяет элементы массива элементами других переданных массивов
  • array_combine() — Создаёт новый массив, используя один массив в качестве ключей, а другой для его значений

User Contributed Notes 8 notes

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.

$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.

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

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:

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:

The keys will keep the same, the order will keep the same, but with a little caveat: The keys will be converted to integers.

We no longer need array_merge() as of PHP 7.4.

does the same as

and can be faster too.

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

If you’re trying to merge an array with something that evaluates to NULL, you’ll get unpredictable results:

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.

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

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


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:

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):

While it’s perfectly legitimate to merge empty arrays, null is *not* an empty array!

# Processing Multiple Arrays Together

array_merge overwrites the values of the first array with the values of the second array, if it cannot renumber the index.

You can use the + operator to merge two arrays in a way that the values of the first array never get overwritten, but it does not renumber numeric indexes, so you lose values of arrays that have an index that is also used in the first array.

# Array intersection

The array_intersect function will return an array of values that exist in all arrays that were passed to this function.

Array keys are preserved. Indexes from the original arrays are not.

array_intersect only check the values of the arrays. array_intersect_assoc function will return intersection of arrays with keys.

array_intersect_key function only check the intersection of keys. It will returns keys exist in all arrays.

# Changing a multidimensional array to associative array

If you have a multidimensional array like this:

And you want to change it to an associative array like this:

You can use this code:

Or, you can skip setting $associativeArrayKeys and $associativeArrayValues and use this simple one liner:

# Combining two arrays (keys from one, values from another)

The following example shows how to merge two arrays into one associative array, where the key values will be the items of the first array, and the values will be from the second:

PHP array_merge

Summary: in this tutorial, you will learn how to use the PHP array_merge() function to merge one or more arrays into one.

Introduction to the PHP array_merge() function

To merge one or more arrays into an array, you use the array_merge() function:

The array_merge() function accepts one or more arrays and returns a new array that contains the elements from the input arrays.

The array_merge() function appends the elements of the next array to the last element of the previous one.

When the elements in the input arrays have the string keys, the later value for that key will overwrite the previous one.

However, if the array_merge() function will not overwrite the values with the same numeric keys. Instead, it renumbers the numeric keys starting from zero in the result array.

Starting from PHP 7.4.0, you can call the array_merge() function without any arguments. In this case, the function will return an empty array.

PHP array_merge() function examples

Let’s take some examples of using the array_merge() function.

1) Simple array_merge() function example

The following example uses the array_merge() function to merge two arrays into one:

  • First, define two indexed arrays: $server_side and $client_side .
  • Second, merge the $server_side and $client_side arrays into one array using the array_merge() function.
  • Third, show the result array.

As you can see clearly from the output, the array_merge() function renumbers the numeric keys of the elements in the result array.

2) Using array_merge() function with string keys

The following example uses the array_merge() function with the array with the string keys:

Because both $before and $after arrays have the same elements with the same string keys PHP and JavaScript , the elements in the $after array overwrites the ones in the $before array.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *