iterator_count

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

iterator_countContar los elementos de un iterador

Descripción

iterator_count(Traversable $iterator): int

Contar los elementos de un iterador. iterator_count() no garantiza conservar la posición actual de iterator.

Parámetros

iterator

El iterador a contar.

Valores devueltos

El número de elementos de iterator.

Ejemplos

Ejemplo #1 Ejemplo de iterator_count()

<?php
$iterator
= new ArrayIterator(array('recipe'=>'panqueques', 'huevo', 'leche', 'harina'));
var_dump(iterator_count($iterator));
?>

El resultado del ejemplo sería:

int(4)

Ejemplo #2 iterator_count() modifica la posición

<?php
$iterator
= new ArrayIterator(['uno', 'dos', 'tres']);
var_dump($iterator->current());
var_dump(iterator_count($iterator));
var_dump($iterator->current());
?>

El resultado del ejemplo sería:

string(3) "uno"
int(3)
NULL

Ejemplo #3 iterator_count() en bucles foreach

<?php
$iterator
= new ArrayIterator(['uno', 'dos', 'tres']);
foreach (
$iterator as $clave => $valor) {
echo
"$clave: $valor (", iterator_count($iterator), ")\n";
}
?>

El resultado del ejemplo sería:

0: uno (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