Introduction to Queues in PHP

Introduction to Queues

Hello there! Today, we will unveil Queues in coding, likening them to a line in a coffee shop or a queue of print requests. Queues in computer science are First-In, First-Out (FIFO) structures. Consider this example: you're at a theme park — the first person in line for the roller coaster gets on first. Today's lesson revolves around this straightforward yet powerful concept. So, let's dive in!

Implementing a Queue in PHP

Let's explore the implementation of Queues in PHP. An array is ideal for implementing a Queue. Let's define the Queue:

class Queue {
    private $queue;
    private $size;
    private $capacity;

    public function __construct($capacity) {
        $this->capacity = $capacity;
        $this->queue = [];
        $this->size = 0;
    }

    // Will return true if the Queue is full
    public function isFull() {
        return $this->size == $this->capacity;
    }
}

In the Queue class above, the isFull() method checks if our queue is already at maximum capacity.

Queue Enqueue Operation

Queue Dequeue Operation

Just as enqueue adds an element to our queue, dequeue removes it. It extracts the element at the queue's beginning, reducing its size. However, we encounter an underflow condition if there are no elements to remove.

public function dequeue() {
    if ($this->isEmpty()) // Check if the queue is empty
        return null;

    $this->size--; // Decrement size
    return array_shift($this->queue); // Remove and return the first item
}

public function isEmpty() {
    return $this->size == 0;
}

The dequeue() method checks for emptiness before dispatching the item.

Complexity Analysis of Queue Operations

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal