Skip to content
Tutorials Center
My learning

Topics

PHP Reference ยท Array Functions

PHP array_pop() function

Reference for PHP array_pop(): remove and return the last element of an array, what happens on empty arrays, key behavior and use as a stack.

The array_pop() function removes the last element of an array and returns it. The array is passed by reference, so it becomes one element shorter. Together with array_push() it turns an array into a stack (last in, first out).

If the array is empty, nothing is removed and the function returns null. That is also what you get when the last element really is null, so use count() or $array === [] when the difference matters.

PHP
$stack = ["a", "b", "c"];
$last = array_pop($stack); // "c"
print_r($stack);           // ["a", "b"]

Try it

PHP Using an array as a stack

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

PHP Keys after popping

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Syntax

PHP
array_pop(array &$array): mixed
Name Description
$array The array to shorten, passed by reference.

Return value: the removed value, or null if the array was empty.

Errors / Exceptions: a TypeError if the argument is not an array.

Usage notes

  • Cheap operation. Removing from the end does not renumber the remaining elements, so it is fast even for large arrays.
  • The next automatic key is reset. After popping, the internal "next index" is recalculated, so $a[] = ... reuses the freed number when the popped key was the highest integer key (see the example above).
  • Keys are kept. Remaining string and integer keys are not renumbered; use array_values() if you want a fresh list.
  • null is ambiguous. An empty array and a popped null both give null.
  • Needs a variable, not a literal or a function result.
  • To read the last element without removing it, use end() or $array[array_key_last($array)] (see array_key_last()).
  • Opposite end: array_shift() removes the first element, but it renumbers integer keys and is slower on large lists.
  • For real queues and stacks with many operations, SplStack, SplQueue or SplDoublyLinkedList express intent better.