CKTIS / PHP
SplQueue::dequeue — remove and return the front item
`dequeue()` removes the front item from a FIFO queue and returns its value. An empty queue throws `RuntimeException`, while `null` can be a legitimate stored value.
Version: PHP 8.3
Syntax
public function dequeue(): mixed
$value = $queue->dequeue();In PHP 8.3, SplQueue::dequeue is a public instance method of the SPL class \SplQueue. SPL is built into PHP 8.3 and cannot be disabled. Call $queue->dequeue() with no arguments to remove one item from the front and return its value as mixed. Since enqueue() adds items at the back, they come out in insertion order (FIFO).
The method is an alias of SplDoublyLinkedList::shift(). To read the front item without removing it, use the inherited bottom() method. By contrast, pop() removes and returns the item at the opposite end.
Calling dequeue() on an empty queue throws \RuntimeException. If an empty queue is expected, check isEmpty() before removing an item. A returned null or false can be a stored value, not a signal that the queue is empty.
Examples
<?php
$queue = new \SplQueue();
$queue->enqueue('A');
$queue->enqueue(null);
$queue->enqueue('B');
while (!$queue->isEmpty()) {
echo var_export($queue->dequeue(), true), "\n";
}
try {
$queue->dequeue();
} catch (\RuntimeException $exception) {
echo get_class($exception), "\n";
}
Result
'A' NULL 'B' RuntimeException
The loop prints all three values in insertion order, including `NULL`. The final call deliberately skips the `isEmpty()` check and prints the class name of the caught exception.
Related lessons
- PHP · Lesson 65 · Advanced · Version: 2