CKTIS / PHP
SplStack::pop — Remove the top item from a stack
Remove the top item from a stack and return its value. Calling this method on an empty stack throws a `\RuntimeException`.
Version: PHP 8.3
Syntax
$value = $stack->pop(); // $stack is a \SplStack
// Inherited signature: public function SplDoublyLinkedList::pop(): mixedSplStack::pop is a public instance method inherited from SplDoublyLinkedList. Call $stack->pop() with no arguments on an SPL \SplStack object. It removes the last node of the doubly linked list, which is the top of the stack, and returns the stored value as mixed.
push() adds an item to the top. When you use only push() and pop(), items come out in the reverse order they went in: last in, first out (LIFO). Use top() when you want to read the top value without removing it.
On an empty stack, both pop() and top() throw \RuntimeException. null can be a stored value, so it does not signal an empty stack. If an empty stack is an expected case, check isEmpty() before calling either method.
Examples
<?php
$stack = new \SplStack();
$stack->push(10);
$stack->push(20);
echo 'top: ', $stack->top(), "\n";
while (!$stack->isEmpty()) {
echo 'pop: ', $stack->pop(), "\n";
}
try {
$stack->pop();
} catch (\RuntimeException $exception) {
echo "empty: RuntimeException\n";
}
Result
top: 20 pop: 20 pop: 10 empty: RuntimeException
In the PHP 8.3 CLI example, `top()` shows `20` without removing it. The loop then pops `20` and `10`, and the final call deliberately pops from an empty stack to show the exception being caught.
Related lessons
- PHP · Lesson 64 · Advanced · Version: 2