CKTIS / PHP
SplStack::top — read the top of a stack without removing it
`SplStack::top` returns the value at the top of a stack without removing the element. On an empty stack it throws `\RuntimeException`.
Version: PHP 8.3
Syntax
public function top(): mixed
$stack->top()SplStack::top is a public instance method inherited from SplDoublyLinkedList. Call it on an object as $stack->top(), with no arguments. It returns the value of the last node in the doubly linked list, which is the top of the stack, and leaves that node in place.
push() adds an element to the top. With last-in, first-out (LIFO) ordering, the last element pushed is the first one removed. Use top() to inspect the value and pop() to return it and remove the element. Unlike current(), top() does not depend on the iterator's position.
The return type mixed includes null, so null can be a stored value and does not indicate an empty stack. On an empty stack, top() throws \RuntimeException. If an empty stack is expected, check isEmpty() before calling it.
The example targets PHP 8.3, which has SPL built in. In namespaced code, use the fully qualified names \SplStack and \RuntimeException, or import those classes.
Examples
<?php
$stack = new \SplStack();
$stack->push('A');
$stack->push('B');
echo $stack->top(), "\n";
echo $stack->top(), "\n";
echo $stack->pop(), "\n";
echo $stack->top(), "\n";
$stack->pop();
try {
$stack->top();
} catch (\RuntimeException $exception) {
echo "RuntimeException\n";
}
Result
B B B A RuntimeException
The two `top()` calls print `B`. The first `pop()` prints and removes `B`, so the next `top()` prints `A`. After `A` is removed, the `catch` block prints the fixed text `RuntimeException`, not the exception message.
Related lessons
- PHP · Lesson 64 · Advanced · Version: 2