php8.5
Home/ Manual/ spl / functions/ iterator_count

iterator_count

PHP function Edit on GitHub ✎

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

Count the elements in an iterator

Description

iterator_count(Traversable|array $iterator): int

Count the elements in an iterator. iterator_count() is not guaranteed to retain the current position of the iterator.

Parameters

iterator

The iterator being counted.

Return Values

The number of elements in iterator.

Changelog

VersionDescription
8.2.0The type of iterator has been widened from Traversable to Traversable|array.

Examples

iterator_count() example

php
<?php
$iterator = new ArrayIterator(array('recipe'=>'pancakes', 'egg', 'milk', 'flour'));
var_dump(iterator_count($iterator));
?>

The above example will output:

output
int(4)

iterator_count() modifies position

php
<?php
$iterator = new ArrayIterator(['one', 'two', 'three']);
var_dump($iterator->current());
var_dump(iterator_count($iterator));
var_dump($iterator->current());
?>

The above example will output:

output
string(3) "one"
int(3)
NULL

iterator_count() in Foreach loops

php
<?php
$iterator = new ArrayIterator(['one', 'two', 'three']);
foreach ($iterator as $key => $value) {
    echo "$key: $value (", iterator_count($iterator), ")\n";
}?>

The above example will output:

output
0: one (3)

Source: reference/spl/functions/iterator-count.xml · from the official PHP manual (php/doc-en)