A Queue is a simple data structure where the first item added is the first one
removed, also known as First In First Out (FIFO).
Requirements: You need PHP 7 for the extension and compatibility.
Installation: The easiest way to install the data structure is by using
the PECL extension.
pecl install ds
Syntax:
public Ds\Queue::functionname()
Example: Here’s how to use the
`Ds\Queue::clear()`
function in
PHP:
<?php // Create a new Queue $q = new \Ds\Queue(); // Add items to the Queue $q->push("One"); $q->push("Two"); $q->push("Three"); echo "Initial Queue:\n"; // Show the Queue print_r($q); // Clear the Queue $q->clear(); echo "\nQueue after clearing:\n"; print_r($q); ?>
Output:
Initial Queue: Ds\Queue Object ( [0] => One [1] => Two [2] => Three ) Queue after clearing: Ds\Queue Object ( )
Complete list of data structure DS\Queue:
Ds\Queue Functions | Description |
---|---|
allocate(size) | Allocate memory for the queue to hold a specific number of elements (`size`). This pre-allocates space to potentially avoid performance overhead during insertions or removals. |
capacity() | Return the current maximum number of elements the queue can hold without needing reallocation. |
clear() | Remove all elements from the queue. |
copy() | Create a new queue that is a shallow copy of the original queue. Changes to the original queue will not be reflected in the copy, and vice versa. |
count() | Return the number of elements currently in the queue. |
isEmpty() | Check whether the queue is empty (contains no elements). |
peek() | Return the first element in the queue (same as get(0)). If the queue is empty, it may return an error or null value. |
pop() | Remove and return the first element from the queue. If the queue is empty, it may return an error or null value. |
push(value) | Add a new element to the end (back) of the queue. |
toArray() | Convert the queue to a regular PHP array. The elements will be in the same order they were inserted (First In First Out - FIFO). |