array ( 0 => 'index.php', 1 => 'PHP Manual', ), 'head' => array ( 0 => 'UTF-8', 1 => 'zh', ), 'this' => array ( 0 => 'function.iterator-count.php', 1 => 'iterator_count', ), 'up' => array ( 0 => 'ref.spl.php', 1 => 'SPL 函数', ), 'prev' => array ( 0 => 'function.iterator-apply.php', 1 => 'iterator_apply', ), 'next' => array ( 0 => 'function.iterator-to-array.php', 1 => 'iterator_to_array', ), 'alternatives' => array ( ), 'source' => array ( 'lang' => 'zh', 'path' => 'reference/spl/functions/iterator-count.xml', ), ); $setup["toc"] = $TOC; $setup["toc_deprecated"] = $TOC_DEPRECATED; $setup["parents"] = $PARENTS; manual_setup($setup); ?>
(PHP 5 >= 5.1.0, PHP 7, PHP 8)
iterator_count — 计算迭代器中元素的个数
对迭代器中的元素计数。iterator_count() 不能保留
iterator
的当前位置。
iterator
要计数的迭代器。
iterator
中的元素个数。
版本 | 说明 |
---|---|
8.2.0 |
iterator 的类型从 Traversable
扩展为 Traversable|array。
|
示例 #1 iterator_count() 示例
<?php
$iterator = new ArrayIterator(array('recipe'=>'pancakes', 'egg', 'milk', 'flour'));
var_dump(iterator_count($iterator));
?>
以上示例会输出:
int(4)
示例 #2 iterator_count() 修改位置
<?php
$iterator = new ArrayIterator(['one', 'two', 'three']);
var_dump($iterator->current());
var_dump(iterator_count($iterator));
var_dump($iterator->current());
?>
以上示例会输出:
string(3) "one" int(3) NULL
示例 #3 iterator_count() 在 foreach 中循环
<?php
$iterator = new ArrayIterator(['one', 'two', 'three']);
foreach ($iterator as $key => $value) {
echo "$key: $value (", iterator_count($iterator), ")\n";
}?>
以上示例会输出:
0: one (3)