Stacks and Queues
Queue Enqueue/Dequeue
Enqueue values at the back and dequeue them from the front in first-in, first-out order.
Algorithm
The replay uses the same three values in every language, so this PHP DSA implementation can be compared directly with the rest of the DSA track.
front
The front is the oldest value still waiting in the queue.
FIFO
A queue removes values in first-in, first-out order.
Visual walkthrough
Basic Implementation
basic.php
<?php
function render_values(array $values): string { return implode(" -> ", $values); }
$queue = [];
foreach ([10, 20, 30] as $value) { $queue[] = $value; }
$removed = [];
while (count($queue) > 0) { $removed[] = array_shift($queue); }
echo render_values($removed) . PHP_EOL;
Complexity
- Time: O(1) per operation with a real queue
- Space: O(n)
Implementation notes
$queue = []starts as an empty PHP array, and the trace records that exact empty state first.- The enqueue loop is
foreach ([10, 20, 30] as $value) { $queue[] = $value; }, so each value is appended at the back of the same array. - After enqueue, the replayed queue state is
[10, 20, 30]. $removed = []collects the dequeue order separately from the live queue.- The dequeue loop runs while
count($queue) > 0and usesarray_shift($queue)to remove the front element. - In PHP,
array_shiftmutates the array by removing the first value; with these numeric positions, the remaining values slide forward in queue order. - That makes the source easy to replay for three pinned values, but it is not the scalable PHP queue shape; a larger queue would keep a head index or use a real queue container instead of shifting the array each time.
- The first dequeue moves
10into$removed, leaving$queueas[20, 30]. - The remaining dequeues produce
$removed = [10, 20, 30]and$queue = []. render_values($removed)joins values with" -> ", andecho ... . PHP_EOLprints10 -> 20 -> 30.