PHP

Implement a Basic FIFO Queue with PHP Arrays

Discover how to simulate a First-In, First-Out (FIFO) queue data structure efficiently in PHP using core array functions `array_push` to enqueue and `array_shift` to dequeue elements.

<?php
// Initialize an empty queue
$queue = [];

// Enqueue (add elements to the end of the queue)
array_push($queue, 'Task A');
array_push($queue, 'Task B');
array_push($queue, 'Task C');

echo "Current queue: ";
print_r($queue);
// Expected: Current queue: Array ( [0] => Task A [1] => Task B [2] => Task C )

// Dequeue (remove elements from the front of the queue)
$nextTask = array_shift($queue);
echo "Dequeued: " . $nextTask . "
"; // Dequeued: Task A

$nextTask = array_shift($queue);
echo "Dequeued: " . $nextTask . "
"; // Dequeued: Task B

echo "Queue after dequeuing: ";
print_r($queue);
// Expected: Queue after dequeuing: Array ( [0] => Task C )

// Check if queue is empty
if (empty($queue)) {
    echo "Queue is empty.
";
} else {
    echo "Queue is not empty. Next item: " . current($queue) . "
";
}
?>
How it works: This snippet illustrates how to implement a basic First-In, First-Out (FIFO) queue using PHP's built-in array functions. `array_push()` is used to 'enqueue' new elements at the end of the array, while `array_shift()` is used to 'dequeue' elements from the beginning. This pattern is commonly used in task scheduling, message processing, or managing sequential operations where the order of processing is critical.

Need help integrating this into your project?

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

Hire DigitalCodeLabs