Implementing Practical Problems Using PHP Data Structures

Introduction to Practice Problems

Welcome to the practical segment of our PHP programming journey! Today, we'll apply the knowledge from past lessons to solve two practice problems using PHP's data structures: queues with SplQueue, deques using SplDoublyLinkedList, and associative arrays for managing ordered data.

First Practice Problem: Using Queues

Consider an event-driven system, like a restaurant. Orders arrive, and they must be handled in the order they were received, following the First In, First Out (FIFO) principle. This principle makes it a perfect scenario for a queue implementation using PHP's SplQueue.

<?php

class Queue
{
    private $buffer;

    public function __construct()
    {
        // Initializing an empty queue
        $this->buffer = new SplQueue();
    }

    // Adding (enqueueing) an item to the queue
    public function enqueue($val)
    {
        $this->buffer->enqueue($val);
    }

    // Removing (dequeuing) an item from the queue
    public function dequeue()
    {
        if ($this->isEmpty()) {
            throw new UnderflowException("Queue is empty");
        }
        return $this->buffer->dequeue();
    }

    // Checking if the queue is empty
    public function isEmpty()
    {
        return $this->buffer->isEmpty();
    }

    // Checking the size (number of items) in the queue
    public function size()
    {
        return $this->buffer->count();
    }
}

$restaurantQueue = new Queue();
$restaurantQueue->enqueue("Order 1");
$restaurantQueue->enqueue("Order 2");

echo "Dequeued: " . $restaurantQueue->dequeue() . PHP_EOL;
echo "Dequeued: " . $restaurantQueue->dequeue() . PHP_EOL;

This code demonstrates the creation and operation of a Queue class, which utilizes PHP's SplQueue to efficiently implement a queue. The Queue class includes methods to enqueue (add) an item, dequeue (remove) an item, check if the queue is empty, and return the queue's size. Enqueue operations add an item to the queue (simulating the arrival of a new order), while dequeue operations remove an item from the front (simulating the serving of an order), maintaining the First In, First Out (FIFO) principle.

Analyzing the First Problem Solution

We've mimicked a real-world system by implementing a queue using PHP's SplQueue. The enqueuing of an item adheres to the FIFO principle, similar to the action of receiving a new order at a restaurant. The dequeuing serves an order, reflecting the preparation and delivery of the order.

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