PHP
Implement a Basic FIFO Queue Using PHP Array Functions
Learn to build a First-In-First-Out (FIFO) queue data structure in PHP using `array_push` and `array_shift` for efficient task processing.
class SimpleQueue {
private array $queue = [];
public function enqueue(mixed $item): void {
array_push($this->queue, $item);
echo "Enqueued: " . (is_array($item) ? json_encode($item) : $item) . "
";
}
public function dequeue(): mixed {
if ($this->isEmpty()) {
echo "Queue is empty.
";
return null;
}
$item = array_shift($this->queue);
echo "Dequeued: " . (is_array($item) ? json_encode($item) : $item) . "
";
return $item;
}
public function isEmpty(): bool {
return empty($this->queue);
}
public function size(): int {
return count($this->queue);
}
public function peek(): mixed {
return $this->isEmpty() ? null : $this->queue[array_key_first($this->queue)];
}
}
$taskQueue = new SimpleQueue();
$taskQueue->enqueue("Task A");
$taskQueue->enqueue("Task B");
$taskQueue->enqueue(['id' => 1, 'action' => 'process']);
echo "Queue size: " . $taskQueue->size() . "
";
$taskQueue->dequeue();
$taskQueue->dequeue();
echo "Queue size: " . $taskQueue->size() . "
";
$taskQueue->dequeue();
$taskQueue->dequeue(); // Should show 'Queue is empty.'
/* Expected output:
Enqueued: Task A
Enqueued: Task B
Enqueued: {"id":1,"action":"process"}
Queue size: 3
Dequeued: Task A
Dequeued: Task B
Queue size: 1
Dequeued: {"id":1,"action":"process"}
Queue is empty.
*/
How it works: This snippet demonstrates how to implement a basic First-In-First-Out (FIFO) queue using a PHP array within a `SimpleQueue` class. The `enqueue` method adds an item to the end of the array using `array_push()`, while the `dequeue` method removes an item from the beginning using `array_shift()`. This ensures that the first item added is the first one removed, adhering to the FIFO principle. Helper methods `isEmpty()`, `size()`, and `peek()` are included for practical queue management, making it suitable for managing sequences of operations or messages.