PHP

Implement a First-In, First-Out (FIFO) Queue with PHP Arrays

Discover how to simulate a basic FIFO queue data structure in PHP using standard array functions `array_push` to add elements and `array_shift` to remove them, maintaining insertion order.

<?php
class FifoQueue
{
    private array $queue = [];

    /**
     * Adds an element to the end of the queue.
     */
    public function enqueue($item): void
    {
        array_push($this->queue, $item);
    }

    /**
     * Removes and returns the element from the front of the queue.
     * Returns null if the queue is empty.
     */
    public function dequeue()
    {
        return empty($this->queue) ? null : array_shift($this->queue);
    }

    /**
     * Returns the element at the front of the queue without removing it.
     * Returns null if the queue is empty.
     */
    public function peek()
    {
        return empty($this->queue) ? null : $this->queue[0];
    }

    /**
     * Checks if the queue is empty.
     */
    public function isEmpty(): bool
    {
        return empty($this->queue);
    }

    /**
     * Returns the number of elements in the queue.
     */
    public function size(): int
    {
        return count($this->queue);
    }
}

$taskQueue = new FifoQueue();
$taskQueue->enqueue("Task A");
$taskQueue->enqueue("Task B");
$taskQueue->enqueue("Task C");

// echo $taskQueue->dequeue(); // Outputs: Task A
// echo $taskQueue->peek();    // Outputs: Task B
$taskQueue->dequeue();      // Removes Task B
$taskQueue->enqueue("Task D");
// echo $taskQueue->dequeue(); // Outputs: Task C
// echo $taskQueue->dequeue(); // Outputs: Task D
// echo $taskQueue->dequeue(); // Outputs: null
?>
How it works: This class demonstrates a simple First-In, First-Out (FIFO) queue using a PHP array. `enqueue` adds items to the end of the array using `array_push`, while `dequeue` removes items from the beginning using `array_shift`, ensuring the first item added is the first to be removed. `peek` allows viewing the next item without removal.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs