The iterator_count() function is an inbuilt function in PHP that is used to count the number of elements in an iterator. An iterator is an object that is a collection of elements.
Syntax:
iterator_count(Traversable $iterator) : int
Parameters: This function accepts only one parameter which is described below.
- $iterator: The iterator for which you want to count the number of elements. This should be an object that implements the t
raversableinterface, such as an array or an instance of a class that implements iteratororIteratorAggregate.
Return Value: The iterator_count() function returns the number of elements in the iterator if this function successfully executes.
Program 1: The following program demonstrates the iterator_count() function.
<?php
$numbers = [1, 2, 3, 4, 5];
$iterator = new ArrayIterator($numbers);
$numElements = iterator_count($iterator);
echo "Total elements in the iterator: $numElements";
?>
Output
Total elements in the iterator: 5
Program 2: The following program demonstrates the iterator_count() function.
<?php
// Sample string
$text = "GeeksforGeeks";
$iterator = new ArrayIterator(str_split($text));
// Count the total number of characters
// in the string
$numCharacters = iterator_count($iterator);
echo "Total number of characters in the string: $numCharacters";
?>
Output
Total number of characters in the string: 13
Reference: https://www.php.net/manual/en/function.iterator-count.php