downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | conferences | my php.net

search for in the

iterator_to_array> <iterator_apply
[edit] Last updated: Fri, 17 May 2013

view this page in

iterator_count

(PHP 5 >= 5.1.0)

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

说明

int iterator_count ( Traversable $iterator )

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

参数

iterator

要计数的迭代器。

返回值

迭代器iterator中的元素个数。

范例

Example #1 iterator_count() example

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

以上例程会输出:

int(4)



iterator_to_array> <iterator_apply
[edit] Last updated: Fri, 17 May 2013
 
add a note add a note User Contributed Notes iterator_count - [3 notes]
up
1
donovan jimenez
4 years ago
Be careful of thinking of iterators and arrays as completely analogous in your PHP code. iterator_count will NOT return your iterator to its previous state after looping through it for the count. Any iterator implementation that also implements Countable::count isn't required to do so either.

This is clearest in example form:
<?php
$array
= array(
   
1 => 'foo',
   
2 => 'bar'
);

foreach (
$array as $key => $value)
{
    echo
"$key: $value (", count($array), ")\n";
}

$iterator = new ArrayIterator($array);

foreach (
$iterator as $key => $value)
{
    echo
"$key: $value (", iterator_count($iterator), ")\n";
}
?>

outputs:
1: foo (2)
2: bar (2)
1: foo (2)

Notice that because of how iterator_count works we never see the second iterator value because the next call to then Iterator::valid() implementation returns false (its at the end of the iterator).
up
0
Micha Mech
5 years ago
Yes, but ...

Traversable: "Abstract base interface that cannot be implemented alone. Instead it must be implemented by either IteratorAggregate or Iterator."

So You have to implement IteratorAggregate or Iterator because You can not implement Traversable.
up
0
Ard
6 years ago
Note that you that the iterator parameter doesn't need to be of type Aggregate. As the spl documentation on http://www.php.net/~helly/php/ext/spl/ defines it in the following way:

    iterator_count (Traversable $it).

So you can count the number of files in a given directory quite easily:
<?php iterator_count(new DirectoryIterator('path/to/dir/'));    ?>

 
show source | credits | sitemap | contact | advertising | mirror sites