Manipulating PHP arrays: push, pop, shift, unshift

In spite of allowing direct access to individual array element, PHP provides various other interesting ways to deal with arrays. In particular, there are many PHP functions that make it very easy and efficient to use PHP arrays in different ways such as a stack or as a queue etc.

So in this tutorial, we will learn some useful PHP array functions with example.

array_pop


The array_pop function will remove and return the last element of an array.

In this first example you can see how, given an array of 3 elements, the pop function removes the last element (the one with the highest index) and returns it.
$stack = array("orange", "banana", "apple");
$fruit = array_pop($stack);
print_r($stack);


After the operation, the array will be one element shorter from end.
Array
(
[0] => orange
[1] => banana
)

And apple will be assigned to $fruit.

If array is an empty (or is not an array), NULL will be returned.

array_push


The array_push function add one or more elements onto the end of array
$stack = array("orange", "banana");
array_push($stack, "apple");
print_r($stack);


After the operation, the array will be one more element at the last.
Array
(
[0] => orange
[1] => banana
[2] => apple
)


array_shift


The array_shift function Shift the first value of the array off and returns it, shortening the array by one element and moving everything down.
$stack = array("orange", "banana", "apple", "raspberry");
$fruit = array_shift($stack);
print_r($stack);


After the operation, the array will be one element shorter from beginning.
Array
(
[0] => banana
[1] => apple
[2] => raspberry
)


array_unshift


This is the opposite operation of array_shift. The array_unshift function will take one or values and place it at the beginning of the array moving all the other elements to the right.
$queue = array("orange", "banana");
array_unshift($queue, "apple", "raspberry");
print_r($queue);

After the operation, the array will have two more elements at the beginning.
Array
(
[0] => apple
[1] => raspberry
[2] => orange
[3] => banana
)

You may like these posts