Removes and returns the oldest item in a first-in-first-out queue.
The examples focus on the operation itself, including the important distinction: enqueue appends a new item; dequeue removes the oldest.
What It Does
Use the examples below to observe the behavior on a small dataset before extending it to application code.
Syntax and Return Value
SplQueue::dequeue()
The displayed signature describes the API or identifies any correction or optional dependency. When a parameter is optional, supply it only when the task requires it.
Example 1: Basic Use
enqueue appends; dequeue returns and removes the oldest queued value. SplQueue is a FIFO specialization of SplDoublyLinkedList.
<?php
$queue = new SplQueue();
$queue->enqueue('red');
$queue->enqueue('blue');
echo json_encode($queue->dequeue());
echo json_encode(iterator_to_array($queue));
Output from a successful local PHP 8.4 run:
"red"["blue"]
Example 2: Checking Behavior
enqueue appends; dequeue returns and removes the oldest queued value. SplQueue is a FIFO specialization of SplDoublyLinkedList.
<?php
$queue = new SplQueue();
$queue->enqueue('one');
$queue->enqueue('two');
echo json_encode($queue->dequeue());
echo json_encode(iterator_to_array($queue));
Output from a successful local PHP 8.4 run:
"one"["two"]
Example 3: Practical Example
enqueue appends; dequeue returns and removes the oldest queued value. SplQueue is a FIFO specialization of SplDoublyLinkedList.
<?php
$queue = new SplQueue();
$queue->enqueue(3);
$queue->enqueue(7);
echo json_encode($queue->dequeue());
echo json_encode(iterator_to_array($queue));
Output from a successful local PHP 8.4 run:
3[7]
Important Behavior and Edge Cases
An empty queue raises RuntimeException; always verify it has entries before dequeuing.
Comparison with Related Approaches
| Approach | Difference |
|---|---|
| SplQueue::dequeue | Removes and returns the oldest item in a first-in-first-out queue. |
| Related API or alternative | enqueue appends a new item; dequeue removes the oldest. |
Common Beginner Mistakes
| Mistake | Correct approach |
|---|---|
| Ignoring the operation-specific limits | An empty queue raises RuntimeException; always verify it has entries before dequeuing. |
| Confusing it with a related API | enqueue appends a new item; dequeue removes the oldest. |
Key Takeaways
- Removes and returns the oldest item in a first-in-first-out queue.
- An empty queue raises RuntimeException; always verify it has entries before dequeuing.
- enqueue appends a new item; dequeue removes the oldest.
Use SplQueue::dequeue when its documented behavior matches the problem. Test the relevant edge cases in your own runtime before deploying it.