iterator_count

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

iterator_count计算迭代器中元素的个数

说明

iterator_count ( Traversable $iterator ) : int

计算迭代器中的元素个数。

参数

iterator

要计数的迭代器。

返回值

迭代器iterator中的元素个数。

范例

Example #1 iterator_count() example

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

以上例程会输出:

int(4)

User Contributed Notes

info at ensostudio dot ru 16-Oct-2020 12:31
Safe using:
<?php
$cnt
= iterator_count(clone $iterator);
?>
fractile81 at gmail dot com 05-Jun-2020 02:33
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.