In this tutorial, you shall learn about PHP array_pop() function which can delete the last element in an array, with syntax and examples.

PHP array_pop() Function

The PHP array_pop() function pops (deletes) the last element of the given array, and returns the value of popped item.

The original array we pass to array_pop() gets modified. It loses the last item after array_pop() execution.

Syntax of array_pop()

The syntax of array_pop() function is

array_pop( array)

where

ParameterDescription
array[mandatory] The array from which last element has to be popped.

Function Return Value

array_pop() returns the popped item. In case, if the array is empty, array_pop() returns NONE.

ADVERTISEMENT

Examples

1. Pop the last element of given array

In this example, we will take an array with four items. We call array_pop() function with the array passed as argument. We’ll then store the value returned by array_pop() function and print it. Also, as the original array gets modified, with its last item no more present, we will print this array as well, to see the contents.

PHP Program

<?php
$array1 = array("apple", "banana", "mango", "orange");
$key = array_pop($array1);
echo $key;
echo "<br>";
print_r($array1)
?>

Output

PHP array_pop() - Pop the Last Element of Array

2. Pop elements of an Array iteratively in Loop

In this example, we will take an array with four items as in previous example. We will use a For loop to iteratively pop items from the array until the array is empty.

PHP Program

<?php
$array1 = array("apple", "banana", "mango", "orange");
while(sizeof($array1)>0) {
    echo array_pop($array1);
    echo "<br>";
}
?>

Output

PHP array_pop() - Pop Elements of Array Iteratively in Loop

Conclusion

In this PHP Tutorial, we learned how to , using PHP Array array_pop() function.