UnderflowException
PHPERRORCommonBounds
Removing from an empty container
Quick Answer
Check isEmpty() before pop/dequeue; throw UnderflowException to signal an empty container.
What this means
Thrown when an element is removed from or requested on an empty container.
Why it happens
- 1Popping from an empty stack
- 2Dequeuing from an empty queue
Fix
Check before removal
Check before removal
public function pop(): mixed {
if (empty($this->items)) {
throw new \UnderflowException("Cannot pop from an empty stack");
}
return array_pop($this->items);
}Why this works
Explicit empty check prevents undefined behavior and provides a clear error message.
Code examples
SplStack popphp
$s = new \SplStack(); $s->pop(); // RuntimeException: Can't pop from an empty datastructure
Custom guardphp
if ($stack->isEmpty()) {
throw new \UnderflowException("Stack is empty");
}
$val = $stack->pop();Same error in other languages
Sources
Official documentation ↗
PHP Manual
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev