Information



Tags



Share

How to insert new elements to the end of an array in PHP

Advertisement:


read_later

Read Later

Keywords



Keywords



read_later

Read Later

Information

Tags

Share





Advertisement

Advertisement



Definition

While working on a database using PHP and MySQL, you, most of the time, have to collect new information about the user behavior and therefore need to insert the new data to a pre-existing array holding the data of the user. In that regard, there is a specific function in PHP to overcome the hardship of inserting new elements to the end of an array, known as the array_push function. In this tutorial, I will show you how to add new elements to the end of an array using the array_push function without any effort.

Code

array_push() treats array as a stack, and pushes the passed variables onto the end of array. The length of array increases by the number of variables pushed.(1)

Define an array named data.

Add one element or more to the end of the data using the array_push function as explained below.

<-----------PHP----------->

<?php
$data = array("orange", "banana");
array_push($data, "apple", "raspberry", "watermelon", "cherry", "strawberry");
print_r($data);
?>

Result:

Array ( [0] => orange [1] => banana [2] => apple [3] => raspberry [4] => watermelon [5] => cherry [6] => strawberry )

References

(1) https://www.php.net/manual/en/function.array-push.php