Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / PHP

SplQueue::count — Get the queue size

Use `SplQueue::count` to read the current number of elements in a FIFO queue without removing anything. An empty queue returns `0`.

Version: PHP 8.3

Syntax

public function count(): int // The inherited return type is tentative in PHP 8.3.

$queue->count();
\count($queue);

SplQueue::count is a public instance method inherited from SplDoublyLinkedList::count. Call it as $queue->count(): the :: in the symbol name does not make it a static call. The method takes no arguments and returns the current number of elements as an int, including 0 for an empty queue.

Counting does not traverse the queue, move its iterator, or remove entries, even in IT_MODE_DELETE mode. Each enqueued value counts as one entry, even if it is an array. Because SplQueue implements Countable through its parent class, the global function \count($queue) returns the same result. The method takes no counting mode.

In a FIFO queue, enqueue() adds an entry at the back, while dequeue() removes and returns the entry at the front. The result of count() describes the queue at the moment of the call. If you only need to check whether the queue is empty, use $queue->isEmpty(). Unlike counting, calling dequeue() on an empty queue throws a RuntimeException.

The example targets PHP 8.3. The \SplQueue class is part of SPL, which is always enabled in standard PHP 8.3 builds.

Examples

<?php
$queue = new \SplQueue();
echo $queue->count(), "\n";

$queue->enqueue('A');
$queue->enqueue(['B', 'C']);
echo $queue->count(), "\n";
echo \count($queue), "\n";

echo $queue->dequeue(), "\n";
echo $queue->count(), "\n";

Result

0
2
2
A
1

The first result is `0`. After two values are added, both forms of counting return `2`: `['B', 'C']` is one queue entry. `dequeue()` returns `A`, leaving `1` entry.

Related lessons

  • PHP · Lesson 65 · Advanced · Version: 2

Sources