iterator_count

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

iterator_countCount the elements in an iterator

Опис

iterator_count(Traversable|array $iterator): int

Count the elements in an iterator. iterator_count() is not guaranteed to retain the current position of the iterator.

Параметри

iterator

The iterator being counted.

Значення, що повертаються

The number of elements in iterator.

Журнал змін

Версія Опис
8.2.0 The type of iterator has been widened from Traversable to Traversable|array.

Приклади

Приклад #1 iterator_count() example

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

Поданий вище приклад виведе:

int(4)

Приклад #2 iterator_count() modifies position

<?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() in foreach loops

<?php
$iterator
= new ArrayIterator(['one', 'two', 'three']);
foreach (
$iterator as $key => $value) {
echo
"$key: $value (", iterator_count($iterator), ")\n";
}
?>

Поданий вище приклад виведе:

0: one (3)

add a note

User Contributed Notes 2 notes

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

?>
To Top