php add item to array
How to add elements to an empty array in PHP?
If I define an array in PHP such as (I don’t define its size):
Do I simply add elements to it using the following?
9 Answers 9
Both array_push and the method you described will work.
It’s better to not use array_push and just use what you suggested. The functions just add overhead.
Based on my experience, solution which is fine(the best) when keys are not important:
You can use array_push. It adds the elements to the end of the array, like in a stack.
You could have also done it like this:
REMEMBER, this method overwrites first array, so use only when you are sure!
When one wants elements to be added with zero-based element indexing, I guess this will work as well:
Both array_push and the method you described will work.
Above is correct, but below one is for further understanding
Not the answer you’re looking for? Browse other questions tagged php arrays variables or ask your own question.
Linked
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.9.17.40238
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
array_push
(PHP 4, PHP 5, PHP 7, PHP 8)
array_push — Push one or more elements onto the end of array
Description
Parameters
Return Values
Returns the new number of elements in the array.
Changelog
Version | Description |
---|---|
7.3.0 | This function can now be called with only one parameter. Formerly, at least two parameters have been required. |
Examples
Example #1 array_push() example
The above example will output:
See Also
User Contributed Notes 35 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.
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 ];
. which will result in an array that looks like this.
[ «element1» => 1, «element2» => 2, «element3» => 3, «element4» => 4 ]
This is how I add all the elements from one array to another:
If you’re adding multiple values to an array in a loop, it’s faster to use array_push than repeated [] = statements that I see all the time:
$ php5 arraypush.php
X-Powered-By: PHP/5.2.5
Content-type: text/html
Adding 100k elements to array with []
Adding 100k elements to array with array_push
Adding 100k elements to array with [] 10 per iteration
Adding 100k elements to array with array_push 10 per iteration
?>
The above will output this:
Array (
[0] => a
[1] => b
[2] => c
[3] => Array (
[0] => a
[1] => b
[2] => c
)
)
There is a mistake in the note by egingell at sisna dot com 12 years ago. The tow dimensional array will output «d,e,f», not «a,b,c».
Need a real one-liner for adding an element onto a new array name?
Skylifter notes on 20-Jan-2004 that the [] empty bracket notation does not return the array count as array_push does. There’s another difference between array_push and the recommended empty bracket notation.
Empy bracket doesn’t check if a variable is an array first as array_push does. If array_push finds that a variable isn’t an array it prints a Warning message if E_ALL error reporting is on.
So array_push is safer than [], until further this is changed by the PHP developers.
If you want to preserve the keys in the array, use the following:
elegant php array combinations algorithm
A common operation when pushing a value onto a stack is to address the value at the top of the stack.
This can be done easily using the ‘end’ function:
A function which mimics push() from perl, perl lets you push an array to an array: push(@array, @array2, @array3). This function mimics that behaviour.
Add elements to an array before or after a specific index or key:
PHP append one array to another (not array_push or +)
How to append one array to another without comparing their keys?
It just should be something, doing this, but in a more elegant way:
12 Answers 12
array_merge is the elegant way:
Doing something like:
This will also work with any Traversable
A warning though:
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:
you can use array functions like this:
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:
For big array, is better to concatenate without array_merge, for avoid a memory copy.
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.
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.
So, the saga continues, I will start using array_merge from now on!
Как добавить элементы в массив в PHP?
На самом деле, операция присваивания значений элементу массива (array) в PHP происходит так же, как и присваивание значений переменной. Но есть небольшая разница: квадратные скобки ([]), добавляемые после имени переменной массива, в данном случае не понадобятся (в таких скобках обычно указывают индекс/ключ элемента). Если же индекс/ключ указаны не будут, PHP выберет наименьший незанятый числовой индекс, сделав это автоматически:
Таким образом, чтобы добавить элемент путём изменения определенного значения, следует просто присвоить новое значение элементу, который уже существует. А чтобы удалить какой-нибудь элемент PHP-массива с его ключом либо удалить сам массив полностью, применяется функция unset():
Тут нужно отметить, что если элемент добавляется в наш массив без ключа, язык программирования PHP автоматически станет использовать предыдущее самое большое значение ключа типа integer, увеличенное на 1. Когда целочисленные индексы в PHP-массиве отсутствуют, ключом становится 0.
Также учтите, что самое большее целое значение ключа совсем необязательно существует в нашем массиве в данный момент, что бывает при удалении элементов массива. А после удаления элементов переиндексация массива array не происходит. На словах всё достаточно сложно, лучше рассмотреть пример:
В вышеописанном примере используются следующие функции: — array_values() — обеспечивает возвращение индексированного массива, заново индексируя возвращаемый массив числовыми индексами; — print_r() — работает как var_dump, однако осуществляет вывод массивов в более удобочитаемом виде.
Как добавить элементы в конец PHP массива?
Рассмотрим параметры работы:
array Наш входной массив. value1 1-е значение, добавляемое в конец нашего массива array.
Что касается возвращаемых значений, то будет возвращено новое количество элементов в массиве.
Рассмотрим использование array_push() на примере:
Как видите, ничего сложного. Если же интересует более сложная практика, её вы найдёте на нашем курсе по PHP-разработке:
How to insert element into arrays at specific position?
Let’s imagine that we have two arrays:
Now, I’d like to insert array(‘sample_key’ => ‘sample_value’) after third element of each array. How can I do it?
24 Answers 24
array_slice() can be used to extract parts of the array, and the union array operator ( + ) can recombine the parts.
For your first array, use array_splice() :
for the second one there is no order so you just have to do :
And sort the keys by whatever you want.
May not really look perfect, but it works.
Here’s a simple function that you could use. Just plug n play.
This is Insert By Index, Not By Value.
you can choose to pass the array, or use one that you already have declared.
EDIT: Shorter Version:
Now you can test the code using
This function supports:
I recently wrote a function to do something similar to what it sounds like you’re attempting, it’s a similar approach to clasvdb’s answer.
Basically it inserts at a specific point, but avoids overwriting by shifting all items down.
If you don’t know that you want to insert it at position #3, but you know the key that you want to insert it after, I cooked up this little function after seeing this question.
Here’s a codepad fiddle to see it in action: http://codepad.org/5WlKFKfz
Note: array_splice() would have been a lot more efficient than array_merge(array_slice()) but then the keys of your inserted arrays would have been lost. Sigh.
Cleaner approach (based on fluidity of use and less code).
Simplest solution, if you want to insert (an element or array) after a certain key:
Using array_splice instead of array_slice gives one less function call.