略微加速

PHP官方手册 - 互联网笔记

PHP - Manual: iterator_count

2024-11-13

iterator_count

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

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

说明

iterator_count(Traversable $iterator): int

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

参数

iterator

要计数的迭代器。

返回值

迭代器iterator中的元素个数。

范例

示例 #1 iterator_count() example

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

以上例程会输出:

int(4)
add a noteadd a note

User Contributed Notes 2 notes

up
1
info at ensostudio dot ru
1 year ago
Safe using:
<?php
$cnt
= iterator_count(clone $iterator);
?>
up
0
oleksii dot bulba at gmail dot com
9 months 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)

?>

官方地址:https://www.php.net/manual/en/function.iterator-count.php

北京半月雨文化科技有限公司.版权所有 京ICP备12026184号-3