Introduction to PHP – Array Functions Part 2

Guest Posts Paolo Nikko Nuñal

Another function that PHP have is removing and adding elements of an array.  es, you heard it right, Arrays in PHP can quickly eliminate the first element of an array with ease and also add an element. This is possible thanks to the arrayshift and arrayunshift functions. In this tutorial you are going to learn how to deal with shifting arrays without having to manually 'loop' an array.

Syntax:

<?php

$fruits = array("Rotten Apples","Mango","Lemons","Grapes");
array_shift($fruits);
echo var_dump($fruits);
?/>


From the example above, the arrayshift() method removed the "Rotten Apples" since it is the first index of the array. You can use the arrayshift() method to remove unwanted elements that always started on the first index.
On the second hand, the arrayunshift is the opposite of the arrayshift() method since you can add elements with ease.
<!--?php?-->

Syntax:

<?php

$fruits = array("Mango","Lemons","Grapes");
array_unshift($fruits,'Jackfruit');
echo var_dump($fruits);
?/>


The result will place the "Jackfruuit" on the first index of the array. This is pretty useful if you want to insert an element on the first part of  the array. You can use these on Pop() or Stack() programs most especially if you are dealing with data structures. This is similar with Java's Pop,Stack,Push methods.