PHP Examples

Queue in PHP



A queue is a linear dynamic data structure that follows First-In/First-Out (FIFO) principle. In a queue, addition of a new element and deletion of an element occurs at different end which implies that the element which is added first in the queue will be the first to be removed from the queue.

Features of queue

  • It is a dynamic data structure.
  • It has dynamic size.
  • It uses dynamic memory allocation.

Operations of a queue

  • isEmpty(): Checks whether the queue is empty or not.
  • size(): Returns the size of the queue.
  • frontElement(): Returns the front element of the queue. It is the element which will be dequeued next.
  • rearElement(): Returns the rear element of the queue. It is the element behind which next element will be enqueued.
  • EnQueue(x): Adds a new element ‘x’ from the rear side of the queue. Consequently, size of the queue increases by 1.
    Queue EnQueue
  • DeQueue(): Deletes the front element of the queue. Consequently, size of the queue decreases by 1.
    Queue DeQueue

Implementation of queue

<?php

class CreateQueue {
  public $front;
  public $rear;

  public $queue = array();

  function __construct() {
    $this->rear = -1;
    $this->front = -1;
  }

  // create a function to check whether 
  // the queue is empty or not 
  public function isEmpty() {
    if($this->rear == $this->front) {
      echo "Queue is empty. \n";
    } else {
      echo "Queue is not empty. \n";
    }
  }

  //create a function to return size of the queue 
  public function size() {
     return ($this->rear - $this->front);
  }

  //create a function to add new element  
  public function EnQueue($x) {
    $this->queue[++$this->rear] = $x;
    echo $x." is added into the queue. \n";
  }

  //create a function to delete front element  
  public function DeQueue() {
    if($this->rear == $this->front){
      echo "Queue is empty. \n";
    } else {
      $x = $this->queue[++$this->front];
      echo $x." is deleted from the queue. \n";
    }
  }

  //create a function to get front element  
  public function frontElement() {
    if($this->rear == $this->front) {
      echo "Queue is empty. \n";
    } else {
      return $this->queue[$this->front+1];
    }
  }

  //create a function to get rear element   
  public function rearElement() {
    if($this->rear == $this->front) {
      echo "Queue is empty. \n";
    } else {
      return $this->queue[$this->rear];
    }
  }
}

// test the code 
$MyQueue = new CreateQueue();
$MyQueue->EnQueue(10);
$MyQueue->EnQueue(20);
$MyQueue->EnQueue(30);
$MyQueue->EnQueue(40);

$MyQueue->DeQueue();
$MyQueue->isEmpty();
?>

The above code will give the following output:

10 is added into the queue.
20 is added into the queue.
30 is added into the queue.
40 is added into the queue.
10 is deleted from the queue.
Queue is not empty.