PHP iterator_count() Function
Last Updated :
22 Sep, 2023
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
raversable interface, such as an array or an instance of a class that implements iterator or IteratorAggregate.
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
<?php
$numbers = [1, 2, 3, 4, 5];
$iterator = new ArrayIterator($numbers);
$numElements = iterator_count($iterator);
echo "Total elements in the iterator: $numElements";
?>
OutputTotal elements in the iterator: 5
Program 2: The following program demonstrates the iterator_count() function.
PHP
<?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";
?>
OutputTotal number of characters in the string: 13
Reference: https://www.php.net/manual/en/function.iterator-count.php
Explore
Basics
Array
OOPs & Interfaces
MySQL Database
PHP Advance