PHP 7.4.9 Released!

iterator_count

(PHP 5 >= 5.1.0, PHP 7)

iterator_countCount the elements in an iterator

Beschreibung

iterator_count ( Traversable $iterator ) : int

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

Parameter-Liste

iterator

The iterator being counted.

R├╝ckgabewerte

The number of elements in iterator.

Beispiele

Beispiel #1 iterator_count() example

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

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

int(4)

Beispiel #2 iterator_count() modifies position

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

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

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

Beispiel #3 iterator_count() in foreach loops

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

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

0: one (3)

add a note add a note

User Contributed Notes 1 note

up
1
fractile81 at gmail dot com
2 months ago
After using this function, the traversable's pointer will point at the end.  Examples 2 and 3 highlight this using code.

This means that when you call iterator_count($foo)...
- Before a foreach-loop on $foo, the loop will not execute because it's already at the end.  Calling $foo->rewind() will reset the traversable to the beginning.
- Inside a foreach-loop on $foo, the loop will complete the current iteration and not repeat.  Something like $foo->seek($i) can be used to reset the pointer, where $i contains the pointer's value prior to counting.
To Top