iterator_count

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

iterator_count Compte de nombre d'éléments dans un itérateur

Description

iterator_count(Traversable $iterator): int

Compte les éléments dans un itérateur. Il n'est pas garantie que la fonction iterator_count() conserve la position courante de l'itérateur iterator.

Liste de paramètres

iterator

L'itérateur dont il faut compter les éléments.

Valeurs de retour

Le nombre d'éléments dans l'itérateur iterator.

Exemples

Exemple #1 Exemple avec iterator_count()

<?php
$iterator 
= new ArrayIterator(array('recipe'=>'crêpes''oeufs''lait''farine'));
var_dump(iterator_count($iterator));
?>

L'exemple ci-dessus va afficher :

int(4)

Exemple #2 Exemple avec iterator_count() qui modifie la position

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

L'exemple ci-dessus va afficher :

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

Exemple #3 Exemple avec iterator_count() dans une boucle foreach

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

L'exemple ci-dessus va afficher :

0: one (3)

add a note add a note

User Contributed Notes 2 notes

up
2
fractile81 at gmail dot com
3 years 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.
up
0
info at ensostudio dot ru
3 years ago
Safe using:
<?php
$cnt
= iterator_count(clone $iterator);
?>
To Top