00 Votes

PHP: Add new Element to existing Array

Question by Compi | 2016-02-08 at 17:36

It is possible to create a new array with  $arr = array(1, 2, 3) in PHP. After that, the array is containing the three elements 1, 2 and 3.

However, is it also possible to add some more elements to an array that is already existing? I am searching for a way with which I can insert some new items at the end of an array after it has already been created or even processed.

ReplyPositiveNegativeDateVotes
2Best Answer2 Votes

Yes, that is possible.

For me, the easiest way is the following:

$arr = array(1, 2, 3);
$arr[] = 4;
$arr[] = 5;

With that code, you are inserting the new elements at the end of the array. In the example, our array afterwards contains 5 elements, the numbers 1 to 5.
2016-02-09 at 11:47

ReplyPositive Negative
11 Vote

Es geht auch mit der Funktion array_push(). Dieser Funktion kannst du den Array und die neuen Elemente übergeben:

$arr = array(1, 2, 3);

array_push($arr, 4);
array_push($arr, 5);
array_push($arr, 6, 7);

$arr2 = array(8, 9, 10);
array_push($arr, $arr2);

Wie du siehst kannst du mit array_push() auch mehrere Elemente gleichzeitig hinzufügen oder sogar einen kompletten weiteren Array. In diesem Beispiel enthält $arr am Ende die Elemente 1 bis 10.
Last update on 2020-09-03 | Created on 2016-02-09

ReplyPositive Negative
Reply

Related Topics

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.