CKTIS / PHP
SplStack::isEmpty — check whether a stack is empty
`isEmpty()` checks whether an `SplStack` holds zero elements. A stack containing a single `false` value is still non-empty.
Version: PHP 8.3
Syntax
public function isEmpty(): bool
$stack->isEmpty()SplStack::isEmpty is a public instance method inherited from SplDoublyLinkedList. It takes no arguments and returns a bool: true for zero elements and false for one or more. Call it on an object with $stack->isEmpty(), not statically with ::. The example targets PHP 8.3, where SPL is part of PHP core and cannot be disabled. The name \SplStack refers to the class in the global namespace.
The method neither removes elements nor moves the iterator. It checks the contents of the whole stack, not the current iterator position as valid() does. Values such as false, 0, and null still count as elements. The empty($stack) construct does not test whether the stack has zero elements.
Use !$stack->isEmpty() to check that there is an element before calling pop(). Calling pop() on an empty stack throws RuntimeException. Do not treat a returned false as a sign that the stack was empty: it may be the value that was removed.
Examples
<?php
$stack = new \SplStack();
var_dump($stack->isEmpty());
$stack->push(false);
var_dump($stack->isEmpty());
if (!$stack->isEmpty()) {
var_dump($stack->pop());
}
var_dump($stack->isEmpty());
Result
bool(true) bool(false) bool(false) bool(true)
The third line, `bool(false)`, is the value removed from the stack. The second line looks the same but means the stack was not empty before the removal.
Related lessons
- PHP · Lesson 64 · Advanced · Version: 2