Как объединить два ассоциативных массива в php
Перейти к содержимому

Как объединить два ассоциативных массива в php

  • автор:

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 array 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 $before array overwrites the ones in the $after array.

Конкатенация (объединение) массивов в PHP

К стыду своему признаю, что за такими простыми вещами, несмотря на кучу лет практики, мне до сих пор приходится ходить в доку. Пожалуй запишу, как объединять массивы в PHP — вроде бы у меня «письменная память», глядишь и запомню 🙂

Тем более, что в PHP в этом месте есть не очевидные аспекты поведения.

Итак, PHP предлагает для объединения массивов два инструмента: php-функция array_merge и оператор «+» («Union»).

Функция array_merge()

array_merge() принимает аргументами массивы, которые нужно объединить. Магия состоит в том, как обрабатываются ключи:

  • для записей с числовым ключом значение правого массива добавляется в конец левого;
  • для записей со строковым ключом значение правого массива перезаписывает значение левого с аналогичным ключом, если оно есть, если нет — добавляется.

Соответственно, array_merge() можно использовать для конкатенации индексных (indexed) массивов и слияния ассоциативных (associative).

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

Оператор сложения массивов (Union): $arr1 + $arr2

Поведение описано вот тут. Принцип такой:

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

Конкатенация (объединение) массивов

Как видим, ни один из этих инструментов не позволяет выполнить конкатенацию массивов. В статье вики по предыдущей ссылке есть требование:

Из-за объединения по ключам и array_merge(), и union могут вернуть результат произвольной длины.

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

Можно пользоваться по необходимости. Но вообще лучше избегать массивов со смешанными ключами, инфа 100% 🙂

А вот табличка, демонстрирующая три описанных выше метода:

Вот так. Если, прочитав это, вы решили срочно сварить немного коррозионностойкой стали, или например кусок углеродистой стали с титаном, ваш выбор — это аргонодуговая сварка электродом, ничего лучше не найдете, поскольку вольфрамовый электрод — это сила!

array_merge

Merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one. It returns the resulting array.

If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.

Values in the input arrays with numeric keys will be renumbered with incrementing keys starting from zero in the result array.

Parameters

Variable list of arrays to merge.

Return Values

Returns the resulting array. If called without any arguments, returns an empty array .

Changelog

Version Description
7.4.0 This function can now be called without any parameter. Formerly, at least one parameter has been required.

Examples

Example #1 array_merge() example

The above example will output:

Example #2 Simple array_merge() example

Don't forget that numeric keys will be renumbered!

If you want to append array elements from the second array to the first array while not overwriting the elements from the first array and not re-indexing, use the + array union operator:

The keys from the first array will be preserved. If an array key exists in both arrays, then the element from the first array will be used and the matching key's element from the second array will be ignored.

Example #3 array_merge() with non-array types

The above example will output:

See Also

  • array_merge_recursive() — Merge one or more arrays recursively
  • array_replace() — Replaces elements from passed arrays into the first array
  • array_combine() — Creates an array by using one array for keys and another for its values

User Contributed Notes 7 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.

How to merge an array in PHP?

To merge arrays, PHP has provided inbuilt functions that will take arrays and will provide final output as a merged array. In this tutorial, we’ll see how to merge an array in PHP.

PHP has provided different functions to group different arrays into single.

  • array_merge()
  • array_combine()
  • array_merge_recursive()

Merge two arrays using array_merge()

We can merge two or more arrays using array_merge() and its syntax is quite simple-

Here, we can pass as many arrays (as arguments) as possible and the expected output will always be an array.

So, in array_merge() the resultant array will contain one array appended to another array which means the first array argument will be considered as a parent/reference array to which all the other array elements will be appended.

Exit fullscreen mode

Now, consider a situation wherein the second array, the same string key is present. So, in such cases, the latter will override the first value.

In the below example, let’s see how to merge associative array in php.

Exit fullscreen mode

However, if the arrays contain numeric keys, the later value will not overwrite the previous/original value, but it will be appended and a new index will be allocated to it.

Exit fullscreen mode

So, we can see that we have two same numeric and string keys in $arr1 & $arr2 . But in the case of numeric keys, it gets appended and for strings keys, it gets overrides.

Now, if the provided array does not have numeric/string keys and only has values like [‘NY’, ‘AL’, ‘AR’] then those will be indexed in increment order.

Exit fullscreen mode

Merge multidimensional array in php

Merging a multidimensional array is the same as that of a simple array. It takes two arrays as input and merges them.

In a multidimensional array, the index will be assigned in increment order and will be appended after the parent array.

Exit fullscreen mode

Now, let’s take the example of an employee who has two addresses. One is his/her permanent address and another is work address. Now, we fetched both the addresses and try to merge them in a single array.

Exit fullscreen mode

Well, it looks weird right. We wanted to get both the address merged into a single array. But this is not going to happen because as we can see both the array keys are the same and are string keys. So the quickest solution will be to store both the address in different indexes.

Exit fullscreen mode

Otherwise user another useful PHP function to merge array recursively i.e, array_merge_recursive()

Merge two arrays using array_merge_recursive()

Now, we’ll use the same above example and see how array_merge_recursive() work efficiently to not override the parent key instead it uses the same key and add those different values inside it as an array.

Exit fullscreen mode

Now, suppose we have an array value for address ‘LA’ inside our first array $permanent_location as follows then that value will also get recursively merged to the same key (address)

Exit fullscreen mode

Combine arrays using array_combine()

array_combine() is used to creates an array by using one array for keys and another for its values.

So, we can use this function in different situations like user profile page where the user’s id, name, and address can be stored in one array and users’ actual information can be stored in another array.

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

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