The feature illustrated below operates on PHP values, objects, or language metadata.
What Is iterator_count in PHP?
Counts elements from an array or Traversable, consuming iterator state where applicable.
iterator_count(Traversable|array $iterator) : int
Parameters:
$iterator— Required. The iterator to attach or traverse.
Return type: int. Counting a non-rewindable iterator may consume its values.
Example 1: Understanding the Basic Behavior
<?php
echo iterator_count(new ArrayIterator([10,20,30]));
Output:
3
Explanation: Counts elements from an array or Traversable, consuming iterator state where applicable.
Example 2: Testing Another Case
<?php
$iterator = new ArrayIterator(['a','b']);
echo iterator_count($iterator);
$iterator->rewind();
echo $iterator->current();
Output:
2a
Explanation: Counting a non-rewindable iterator may consume its values.
Practical Example: Applying the Operation
<?php
function generateItems(): Generator { yield 'one'; yield 'two'; }
echo iterator_count(generateItems());
Output:
2
Explanation: For Countable collections, count() often avoids traversing every element.
Important Behavior and Edge Cases
- Counting a non-rewindable iterator may consume its values.
- For Countable collections, count() often avoids traversing every element.
Comparison With Related Approaches
| Approach | When to Use It |
|---|---|
iterator_count | Counts elements from an array or Traversable, consuming iterator state where applicable. |
count() | iterator_count() traverses a Traversable; count() uses Countable when available and avoids iteration of countable containers. |
Common Beginner Mistakes
| Mistake | Correct Approach |
|---|---|
| Counting a non-rewindable iterator and expecting to traverse the same values again. | Counting a non-rewindable iterator may consume its values. |
| Choosing count() without checking whether it provides the same result. | iterator_count() traverses a Traversable; count() uses Countable when available and avoids iteration of countable containers. |
Key Takeaways
- Counts elements from an array or Traversable, consuming iterator state where applicable.
- Counting a non-rewindable iterator may consume its values.
- For Countable collections, count() often avoids traversing every element.
The examples demonstrate where iterator_count fits within php programming. Verify the relevant preconditions whenever you adapt the code to real data.