Как в php добавить к массиву другой массив?
Есть несколько способов, чтобы добавить массив в массив при помощи php и все они могут пригодиться для отдельных случаев.
«Оператор +»
Это простой, но коварный способ:
Так добавляются только те ключи, которых еще нет в массиве $a. При этом элементы дописываются в конец массива.
То есть если ключ из массива $b отсутствует в массиве $a, то в результирующем массиве добавится элемент с этим ключом.
Если в массиве $a уже есть элемент с таким ключом, то его значение останется без изменений.
Иными словами от перемены мест слагаемых сумма меняется: $a + $b != $b + $a — это стоит запомнить.
А теперь более подробный пример, чтобы проиллюстрировать это:
Функция array_merge()
Использовать эту функцию можно следующим образом:
Она сбрасывает числовые индексы и заменяет строковые. Отлично подходит для того, чтобы склеить два или несколько массивов с числовыми индексами:
Если входные массивы имеют одинаковые строковые ключи, тогда каждое последующее значение будет заменять предыдущее. Однако, если массивы имеют одинаковые числовые ключи, значение, упомянутое последним, не заменит исходное значение, а будет добавлено в конец массива.
Функция array_merge_recursive
Делает то же самое, что и array_merge только еще и рекурсивно проходит по каждой ветке массива и проделывает то же самое с потомками. Подробная справка по array_merge_recursive
Функция array_replace()
Заменяет элементы массива элементами других переданных массивов. Подробная справка по array_replace.
Функция array_replace_recursive()
То же что и array_replace только обрабатывает все ветки массива. Справка по array_replace_recursive.
array_push
array_push() использует array как стек и добавляет переданные значения в конец массива array . Длина array увеличивается на количество переданных значений. Имеет тот же эффект, что и выражение:
Замечание: Вместо использования array_push() для добавления одного элемента в массив, лучше использовать $array[] = , потому что в этом случае не происходит затрат на вызов функции.
Замечание: array_push() вызовет предупреждение, если первый аргумент не является массивом. Это отличается от поведения конструкции $var[] до PHP 7.1.0, в случае которой будет создан новый массив.
Список параметров
Значения, добавляемые в конец массива array .
Возвращаемые значения
Возвращает новое количество элементов в массиве.
Список изменений
| Версия | Описание |
|---|---|
| 7.3.0 | Теперь эта функция может быть вызвана с одним параметром. Ранее требовалось минимум два параметра. |
Примеры
Пример #1 Пример использования array_push()
Результат выполнения данного примера:
Смотрите также
- array_pop() — Извлекает последний элемент массива
- array_shift() — Извлекает первый элемент массива
- array_unshift() — Добавляет один или несколько элементов в начало массива
User Contributed Notes 36 notes
If you’re going to use array_push() to insert a «$key» => «$value» pair into an array, it can be done using the following:
It is not necessary to use array_push.
I’ve done a small comparison between array_push() and the $array[] method and the $array[] seems to be a lot faster.
<?php
$array = array();
for ( $x = 1 ; $x <= 100000 ; $x ++)
<
$array [] = $x ;
>
?>
takes 0.0622200965881 seconds
<?php
$array = array();
for ( $x = 1 ; $x <= 100000 ; $x ++)
<
array_push ( $array , $x );
>
?>
takes 1.63195490837 seconds
so if your not making use of the return value of array_push() its better to use the $array[] way.
Hope this helps someone.
Rodrigo de Aquino asserted that instead of using array_push to append to an associative array you can instead just do.
. but this is actually not true. Unlike array_push and even.
. Rodrigo’s suggestion is NOT guaranteed to append the new element to the END of the array. For instance.
$data[‘one’] = 1;
$data[‘two’] = 2;
$data[‘three’] = 3;
$data[‘four’] = 4;
. might very well result in an array that looks like this.
[ «four» => 4, «one» => 1, «three» => 3, «two» => 2 ]
I can only assume that PHP sorts the array as elements are added to make it easier for it to find a specified element by its key later. In many cases it won’t matter if the array is not stored internally in the same order you added the elements, but if, for instance, you execute a foreach on the array later, the elements may not be processed in the order you need them to be.
If you want to add elements to the END of an associative array you should use the unary array union operator (+=) instead.
$data[‘one’] = 1;
$data += [ «two» => 2 ];
$data += [ «three» => 3 ];
$data += [ «four» => 4 ];
You can also, of course, append more than one element at once.
$data[‘one’] = 1;
$data += [ «two» => 2, «three» => 3 ];
$data += [ «four» => 4 ];
Note that like array_push (but unlike $array[] =) the array must exist before the unary union, which means that if you are building an array in a loop you need to declare an empty array first.
$data = [];
for ( $i = 1; $i < 5; $i++ ) <
$data += [ «element$i» => $i ];
>
. which will result in an array that looks like this.
[ «element1» => 1, «element2» => 2, «element3» => 3, «element4» => 4 ]
Unfortunately array_push returns the new number of items in the array
It does not give you the key of the item you just added, in numeric arrays you could do -1, you do however need to be sure that no associative key exists as that would break the assumption
It would have been better if array_push would have returned the key of the item just added like the below function
(perhaps a native variant would be a good idea. )
if(! function_exists ( ‘array_add’ )) <
function array_add (array & $array , $value /*[, $. ]*/ ) <
$values = func_get_args (); //get all values
$values [ 0 ]= & $array ; //REFERENCE!
$org = key ( $array ); //where are we?
call_user_func_array ( ‘array_push’ , $values );
end ( $array ); // move to the last item
$key = key ( $array ); //get the key of the last item
if( $org === null ) <
//was at eof, added something, move to it
return $key ;
>elseif( $org <( count ( $array )/ 2 )) < //somewhere in the middle +/- is fine
reset ( $array );
while ( key ( $array ) !== $org ) next ( $List );
>else <
while ( key ( $array ) !== $org ) prev ( $List );
>
return $key ;
>
>
echo «<pre>\n» ;
$pr = array( ‘foo’ => ‘bar’ , ‘bar’ => ‘foo’ );
echo «Taken array;» ;
print_r ( $pr );
echo «\npush 1 returns » . array_push ( $pr , 1 ). «\n» ;
echo «————————————\n» ;
$pr = array( ‘foo’ => ‘bar’ , ‘bar’ => ‘foo’ );
echo «\npush 2 returns » . array_push ( $pr , 1 , 2 ). «\n» ;
echo «————————————\n» ;
$pr = array( ‘foo’ => ‘bar’ , ‘bar’ => ‘foo’ );
echo «\n add 1 returns » . array_add ( $pr , 2 ). «\n\n» ;
echo «————————————\n» ;
$pr = array( ‘foo’ => ‘bar’ , ‘bar’ => ‘foo’ );
echo «\n add 2 returns » . array_add ( $pr , 1 , 2 ). «\n\n» ;
echo «<pre/>\n\n» ;
?>
Outputs:
Taken array;Array
(
[foo] => bar
[bar] => foo
)
PHP append one array to another (not array_push or +)
How to append one array to another without comparing their keys?
At the end it should be: Array( [0]=>a [1]=>b [2]=>c [3]=>d ) If I use something like [] or array_push , it will cause one of these results:
It just should be something, doing this, but in a more elegant way:
11 Answers 11
array_merge is the elegant way:
Doing something like:
Will not work, because the + operator does not actually merge them. If they $a has the same keys as $b , it won’t do anything.
![]()
Another way to do this in PHP 5.6+ would be to use the . token
This will also work with any Traversable
A warning though:
- in PHP versions before 7.3 this will cause a fatal error if $b is an empty array or not traversable e.g. not an array
- in PHP 7.3 a warning will be raised if $b is not traversable
Why don’t you want to use this, the correct, built-in method.
![]()
It’s a pretty old post, but I want to add something about appending one array to another:
- one or both arrays have associative keys
- the keys of both arrays don’t matter
you can use array functions like this:
array_merge doesn’t merge numeric keys so it appends all values of $appendArray. While using native php functions instead of a foreach-loop, it should be faster on arrays with a lot of elements.
Addition 2019-12-13: Since PHP 7.4, there is the possibility to append or prepend arrays the Array Spread Operator way:
As before, keys can be an issue with this new feature:
«Fatal error: Uncaught Error: Cannot unpack array with string keys»
array(4) < [1]=>int(1) [4]=> int(2) [5]=> int(3) [6]=> int(4) >
array(3) < [0]=>int(1) [1]=> int(4) [3]=> int(3) >
Output:
![]()
Following on from answer’s by bstoney and Snark I did some tests on the various methods:
ORIGINAL: I believe as of PHP 7, method 3 is a significantly better alternative due to the way foreach loops now act, which is to make a copy of the array being iterated over.
Whilst method 3 isn’t strictly an answer to the criteria of ‘not array_push’ in the question, it is one line and the most high performance in all respects, I think the question was asked before the . syntax was an option.
UPDATE 25/03/2020: I’ve updated the test which was flawed as the variables weren’t reset. Interestingly (or confusingly) the results now show as test 1 being the fastest, where it was the slowest, having gone from 0.008392 to 0.002717! This can only be down to PHP updates, as this wouldn’t have been affected by the testing flaw.
PHP array push: How to Add Elements to Array in PHP
Add elements/items to an array in PHP; In this tutorial, we would like to share with you how to add or push the items/elements to array in PHP.
- Using array_push() with keys in PHP
- Adding elements to an associative array using array_push() in PHP
- Adding elements to a multidimensional associative array in PHP
- Adding elements to a multidimensional array in PHP
- Pushing an array into a multidimensional array in PHP
- Appending one array to another in PHP
How to Add Elements to Array in PHP
Using the array_push(), you can add elements to an array in PHP.
The array_push() function is used to add one or more elements to the end of an array.
The syntax of array_push() is as follows:
The first parameter, array , is the name of the array to which you want to add elements. The second parameter and subsequent parameters are the values that you want to add to the array.
Example 1 of Add Elements to Array using array_push() in PHP
Let’s consider an example where you have an array of colors, and you want to add a few more colors to the array. Here is the code to do this:
The code creates an indexed array called $colors with three initial elements: “red”, “green”, and “blue”. It then uses the array_push() function to add two more elements, “yellow” and “orange”, to the end of the array.
Finally, the code uses the print_r() function to display the contents of the $colors array, including the newly added elements, in a human-readable format.
So, when the code is executed, it will output the following:
This shows that the two new elements (“yellow” and “orange”) have been successfully added to the end of the $colors array.
Example 2 of array push key value pair php using array_push
Sure, here’s an example of using array_push in PHP to add a key-value pair to an array:
This PHP code is creating an empty array and then adding a key-value pair to it using the array_push function. Finally, it prints the array using the print_r function to confirm that the key-value pair was added successfully.
- $myArray = array(); creates an empty array called $myArray .
- array_push($myArray, array(«key» => «value»)); adds an element to the end of $myArray . The element is an array with a single key-value pair, where the key is «key» and the value is «value» .
- print_r($myArray); prints the contents of $myArray , including the newly added key-value pair. The print_r function is used to print the array in a human-readable format.
So, after running this code, the output would be something like:
This shows that $myArray now contains a single element, which is an array with a key-value pair of «key» => «value» .
Example 3 of add element to multidimensional array using array_push
Sure, here’s an example of adding an element to a multidimensional array using array_push() function in PHP:
The above code defines a multidimensional array called $myArray , which contains two inner arrays, each containing three elements.
Then, the array_push() function is used to add a new element “grape” to the first inner array of $myArray . The array_push() function adds an element to the end of an array and returns the new number of elements in the array.
Finally, the updated $myArray is displayed using the print_r() function, which prints the entire contents of the array, including all the nested arrays and their elements.
So, after executing this code, the output will be:
Example 4 of How to push array in multidimensional array using array_push
Sure, here’s an example of how to use the array_push() function in PHP to push an array into a multidimensional array:
- array() function is used to initialize the multidimensional array $multiArray with two nested arrays, each containing three string elements.
- The $newArray is defined as an array containing three string elements, which will be added to the multidimensional array.
- array_push() is a built-in PHP function used to add elements to the end of an array. Here, it’s used to add $newArray to $multiArray .
- The print_r() function is used to output the contents of the $multiArray array, which now includes the added $newArray at the end.
The output of this code will be:
PHP append one array to another | PHP push array into an array
Now, you will take example of push one array to another array or push array into an array without using array_push() function.
Add one array into another array in PHP:
Conclusion
Through this tutorial, you have learned how to add values in array PHP, PHP array push with key, PHP add to an associative array, PHP add to the multidimensional array, array push associative array PHP, PHP array adds key-value pair to an existing array with examples.