Safe using:
<?php
$cnt = iterator_count(clone $iterator);
?>
PHP - Manual: iterator_count
2024-12-22
(PHP 5 >= 5.1.0, PHP 7, PHP 8)
iterator_count — 计算迭代器中元素的个数
iterator
要计数的迭代器。
迭代器iterator
中的元素个数。
示例 #1 iterator_count() example
<?php
$iterator = new ArrayIterator(array('recipe'=>'pancakes', 'egg', 'milk', 'flour'));
var_dump(iterator_count($iterator));
?>
以上例程会输出:
int(4)
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)
?>
官方地址:https://www.php.net/manual/en/function.iterator-count.php