CKTIS / PHP
SplQueue::isEmpty — Check whether a queue is empty
`isEmpty()` checks whether a `SplQueue` contains zero elements. Use it before `dequeue()` to distinguish an empty queue from one that holds `null` or `false`.
Version: PHP 8.3
Syntax
public function isEmpty(): bool
$queue->isEmpty()SplQueue::isEmpty is a public instance method inherited from SplDoublyLinkedList. Call it with no arguments as $queue->isEmpty(), not as a static method. It returns a bool: true when the queue has no elements and false when it has at least one. It neither removes elements nor advances the iterator.
The check is about the queue's current state, not the values it holds: null, false, and 0 still count as elements. $queue->count() === 0 answers the same question, but isEmpty() states the intent directly. The language construct empty($queue) does not check how many elements the SplQueue object holds.
enqueue() adds an element at the back, and dequeue() removes and returns the front element (FIFO: first in, first out). Calling dequeue() on an empty queue throws RuntimeException. To drain the queue, check !$queue->isEmpty() before each removal. The example targets PHP 8.3, where SPL is built in and cannot be disabled. \SplQueue names the class in the global namespace.
Examples
<?php
$queue = new \SplQueue();
var_dump($queue->isEmpty());
$queue->enqueue(null);
$queue->enqueue(false);
var_dump($queue->isEmpty());
while (!$queue->isEmpty()) {
var_dump($queue->dequeue());
}
var_dump($queue->isEmpty());
Result
bool(true) bool(false) NULL bool(false) bool(true)
The new queue reports `true`; after two insertions it reports `false`. The loop prints `NULL` and then `bool(false)`. These are dequeued values; the final `bool(true)` shows that the queue is empty again.
Related lessons
- PHP · Lesson 65 · Advanced · Version: 2