array_pop
Removes the last element of an array and returns it.
Available since: PHP 4
Syntax
array_pop(array &$array): mixedParameters
| Parameter | Type | Description |
|---|---|---|
| $array | array | The array to take the element from. It is passed by reference and modified. |
Return value
mixedThe removed element, or `null` if the array is empty.
Examples
Taking the last element:
<?php
$stack = ['a', 'b', 'c'];
$last = array_pop($stack);
echo $last, "\n";
echo implode(', ', $stack);Output:
c
a, barray_shift() does the same with the first element:
<?php
$queue = ['a', 'b', 'c'];
$first = array_shift($queue);
echo $first, "\n";
echo implode(', ', $queue);Output:
a
b, cNotes
The reverse operations are array_push() (append) and array_unshift() (prepend).
See also
- array_slice — Returns part of an array.
- count — Returns the number of elements in an array.
Related recipes
In the tutorial
- Arrays — Lists and associative arrays in PHP — creating, changing, iterating and useful functions.