PHP 8.1.0 RC 4 available for testing

iterator_count

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

iterator_countConta o número de elementos do iterador

Descrição

iterator_count(IteratorAggregate $iterator): int
Aviso

Esta função não está documentada; somente a lista de argumentos está disponível.

Conta os elementos em um iterador.

Parâmetros

iterator

O iterador a ser contado.

Valor Retornado

O número de elementos no iterator.

add a note add a note

User Contributed Notes 3 notes

up
2
fractile81 at gmail dot com
1 year 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
oleksii dot bulba at gmail dot com
1 month ago
Be aware that counting over NoRewindIterator will make items unavailable:

<?php

$iterator
= new ArrayIterator(['recipe'=>'pancakes', 'egg', 'milk', 'flour']);
$iterator = new NoRewindIterator($iterator);

var_dump($iterator->current());
var_dump(iterator_count($iterator));
var_dump($iterator->current());
$iterator->rewind(); // Does not work because it's NoRewindIterator
var_dump($iterator->current());
var_dump(iterator_count($iterator));

?>

Output:

<?php

/*
string(8) "pancakes"
int(4)
NULL
NULL
*/
int(0)

?>
up
0
info at ensostudio dot ru
1 year ago
Safe using:
<?php
$cnt
= iterator_count(clone $iterator);
?>
To Top