Adds a new item to the end of a first-in-first-out queue.
The examples focus on the operation itself, including the important distinction: dequeue consumes the oldest pending value.
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::enqueue(mixed $value)
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.
Parameters
- value: required.
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');
$queue->enqueue("extra");
echo json_encode(iterator_to_array($queue));
Output from a successful local PHP 8.4 run:
["red","blue","extra"]
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');
$queue->enqueue("extra");
echo json_encode(iterator_to_array($queue));
Output from a successful local PHP 8.4 run:
["one","two","extra"]
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);
$queue->enqueue("extra");
echo json_encode(iterator_to_array($queue));
Output from a successful local PHP 8.4 run:
[3,7,"extra"]
Important Behavior and Edge Cases
Enqueueing never removes old entries, and the queue allows duplicate values.
Comparison with Related Approaches
| Approach | Difference |
|---|---|
| SplQueue::enqueue | Adds a new item to the end of a first-in-first-out queue. |
| Related API or alternative | dequeue consumes the oldest pending value. |
Common Beginner Mistakes
| Mistake | Correct approach |
|---|---|
| Ignoring the operation-specific limits | Enqueueing never removes old entries, and the queue allows duplicate values. |
| Confusing it with a related API | dequeue consumes the oldest pending value. |
Key Takeaways
- Adds a new item to the end of a first-in-first-out queue.
- Enqueueing never removes old entries, and the queue allows duplicate values.
- dequeue consumes the oldest pending value.
Use SplQueue::enqueue when its documented behavior matches the problem. Test the relevant edge cases in your own runtime before deploying it.