Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / PHP

SplQueue::enqueue — append an item to a queue

Add one value to the back of a `SplQueue`. The method changes the queue in place and returns no result; items are taken out in FIFO order.

Version: PHP 8.3

Syntax

public function enqueue(mixed $value): void

In PHP 8.3, SplQueue is an SPL class in the global namespace. In this release, SPL is part of PHP core and cannot be disabled. new \SplQueue() selects that class even from inside another namespace. SplQueue::enqueue is an instance method: $queue->enqueue($value) appends one value to the back of the existing queue. mixed accepts any PHP value, including null, and void means the method returns no result or object for chaining.

enqueue() is an alias of SplDoublyLinkedList::push(). For FIFO (first in, first out), pair it with dequeue(), which removes and returns the item at the front. Do not use pop() in place of dequeue(): pop() removes from the back.

Calling dequeue() on an empty queue throws RuntimeException. If the queue might be empty, check isEmpty() before removing an item. A returned null can be a stored value, not a signal that the queue is empty.

Examples

<?php
$queue = new \SplQueue();
$queue->enqueue('A');
$queue->enqueue('B');

echo $queue->dequeue(), "\n";
$queue->enqueue('C');

while (!$queue->isEmpty()) {
    echo $queue->dequeue(), "\n";
}

Result

A
B
C

After `A` is removed, `B` is still waiting. `C` goes behind `B`, so the loop prints `B` before `C`.

Related lessons

  • PHP · Lesson 65 · Advanced · Version: 2

Sources