PHP Doku:: Count the elements in an iterator - function.iterator-count.html

Verlauf / Chronik / History: (1) anzeigen

Sie sind hier:
Doku-StartseitePHP-HandbuchFunktionsreferenzSonstige GrunderweiterungenStandard PHP Library (SPL)SPL Funktioneniterator_count

Ein Service von Reinhard Neidl - Webprogrammierung.

SPL Funktionen

<<iterator_apply

iterator_to_array>>

iterator_count

(PHP 5 >= 5.1.0)

iterator_countCount the elements in an iterator

Beschreibung

int iterator_count ( Traversable $iterator )

Count the elements in an iterator.

Parameter-Liste

iterator

The iterator being counted.

Rückgabewerte

The number of elements in iterator.

Beispiele

Beispiel #1 iterator_count() example

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

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

int(4)


3 BenutzerBeiträge:
- Beiträge aktualisieren...
donovan jimenez
23.02.2009 18:34
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).
Micha Mech
9.05.2008 12:38
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.
Ard
31.08.2006 12:39
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/'));    ?>



PHP Powered Diese Seite bei php.net
The PHP manual text and comments are covered by the Creative Commons Attribution 3.0 License © the PHP Documentation Group - Impressum - mail("TO:Reinhard Neidl",...)