iterator_count / iterator_apply
iterator_count(Traversable|array $iterator): int / iterator_apply(Traversable $iterator, callable $callback, ?array $args = null): int
Iterator helpers: iterator_count counts elements but consumes a forward iterator (the position does not survive); iterator_apply calls a callback per element (it must return true to continue) and returns the iteration count.
C C23
#include <stdio.h>
#include <string.h>
/* a minimal one-shot cursor: once advanced past the end it stays exhausted */
typedef struct {
const char *s;
size_t pos, len;
} Cursor;
static int cursor_next_word(Cursor *c) {
while (c->pos < c->len && c->s[c->pos] == ' ') c->pos++; /* skip spaces */
if (c->pos >= c->len) return 0; /* exhausted: one-shot */
while (c->pos < c->len && c->s[c->pos] != ' ') c->pos++;
return 1;
}
int main(void) {
Cursor c = {0}; /* zero-initialized buffer */
c.s = "apple banana cherry";
c.len = 19;
int n = 0;
while (cursor_next_word(&c)) n++; /* counting consumes the cursor */
printf("count=%d; second pass=", n);
int again = 0;
while (cursor_next_word(&c)) again++; /* cursor is spent: still zero */
printf("%d\n", again);
return 0;
}
count=3; second pass=0
C++ C++26
#include <iostream>
#include <iterator>
#include <sstream>
#include <vector>
int main() {
// std::istream_iterator is a one-shot input iterator: std::distance walks it once
std::istringstream in("apple banana cherry");
std::istream_iterator<std::string> first(in), last;
std::cout << "count=" << std::distance(first, last) << '\n';
// input iterators are single-pass: take a fresh iterator for another pass
std::istringstream in2("apple banana cherry");
std::cout << "fresh pass="
<< std::distance(std::istream_iterator<std::string>(in2),
std::istream_iterator<std::string>()) << '\n';
std::vector<std::string> v{"apple", "banana", "cherry"};
std::cout << "random-access count=" << std::distance(v.begin(), v.end()) << '\n';
return 0;
}
count=3 fresh pass=3 random-access count=3
C# v11.0.100
using System;
using System.Collections.Generic;
using System.Linq;
IEnumerable<string> Seq()
{
yield return "apple";
yield return "banana";
yield return "cherry";
}
// Count() enumerates the sequence; IEnumerable may be re-enumerated fresh each time
var first = Seq();
Console.WriteLine($"enumerated={first.Count()}");
var second = Seq();
Console.WriteLine($"re-enumerated={second.Count()}");
enumerated=3 re-enumerated=3
Go v1.27.4
package main
import (
"bufio"
"fmt"
"strings"
)
func main() {
// bufio.Scanner is a one-shot iterator: counting consumes it
sc := bufio.NewScanner(strings.NewReader("apple\nbanana\ncherry"))
n := 0
for sc.Scan() {
n++
}
fmt.Println("count=", n, "; scan again=", sc.Scan())
}
count= 3 ; scan again= false
Java v27.0.1
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) {
List<String> data = Arrays.asList("apple", "banana", "cherry");
Stream<String> s1 = data.stream();
System.out.println("stream count=" + s1.count()); // counting consumes the stream
Stream<String> s2 = data.stream(); // streams are one-shot: take a fresh one
System.out.println("second stream count=" + s2.count());
System.out.println("collection size=" + data.size());
}
}
stream count=3 second stream count=3 collection size=3
JavaScript v26.13.1
// a generator is a one-shot iterator: spread consumes it, then it is exhausted
function* items() {
yield "apple";
yield "banana";
yield "cherry";
}
const it = items();
const n = [...it].length;
console.log(`count=${n}; second pass=${[...it].length}`);
count=3; second pass=0
PHP v8.6.0
// iterator_count counts elements but CONSUMES a forward iterator: the
// position does not survive (the iterator walks exactly once).
$it = new ArrayIterator(['pancakes', 'egg', 'milk', 'flour']);
echo 'count=', iterator_count($it), '; current after=', var_export($it->current(), true), "\n";
// iterator_apply walks every element while the callback returns true,
// returning the number of iterations performed.
$it2 = new ArrayIterator(['apple', 'banana', 'cherry']);
$n = iterator_apply($it2, function (Iterator $it) {
echo strtoupper($it->current()), "\n";
return true; // must return true to continue iterating
}, [$it2]);
echo 'applied=', $n;
count=4; current after=NULL APPLE BANANA CHERRY applied=3
Python v3.15.2
# len(list(it)) materializes a generator: generators are one-shot iterators
def items():
yield "apple"
yield "banana"
yield "cherry"
it = items()
print("count=", len(list(it)), "; second pass=", len(list(it)))
count= 3 ; second pass= 0
Rust v1.99.1
// Iterator::count() consumes the iterator: one-shot adapters stay exhausted
fn main() {
let data = vec!["apple", "banana", "cherry"];
let it = data.iter().map(|s| s.to_uppercase());
let n = it.count();
println!("count={n}; reusable=no");
}
count=3; reusable=no
TypeScript v26.13.1
// a generator is a one-shot iterator: spread consumes it, then it is exhausted
function* items(): Generator<string> {
yield "apple";
yield "banana";
yield "cherry";
}
const it = items();
const n: number = [...it].length;
console.log(`count=${n}; second pass=${[...it].length}`);
count=3; second pass=0
Language differences
PHP: iterator_count walks the iterator to its end BEFORE counting — the manual explicitly does not guarantee the position survives (in the example current() is NULL after counting), the same teaching moment as iterator_to_array (see that entry): an iterator walks exactly once, exhausted after counting or copying; NoRewindIterator is even less forgiving. Since 8.2 the parameter is widened to Traversable|array (a plain array works too). iterator_apply is callback-driven traversal: the callback MUST return true to continue (a falsy return stops it), and the return value is the number of iterations — array_walk's iterator flavor; note the callback receives only the explicitly passed third argument, so read elements via current()/key() yourself.
C: no iterator protocol — the example hand-rolls a one-shot cursor struct (once pos passes len it stays exhausted) to demonstrate the counting-consumes semantics; zero-init via Cursor c = {0}.
C++: std::istream_iterator is an input iterator (single-pass) — std::distance walks it once and consumes it, another pass needs a fresh stream; note std::distance is O(1) subtraction on random-access iterators (vector) but an O(n) walk on input iterators — one name, two semantics.
C#: Count() (LINQ) enumerates the whole sequence to count it; unlike PHP, IEnumerable is contractually RE-ENUMERABLE (each GetEnumerator hands out a fresh cursor); the truly one-shot cases are direct enumeration of StreamReader/network streams.
Go: bufio.Scanner (the example) is a one-shot iterator — after Scan hits the end, Scan() stays false forever; no generic iterator protocol (1.23 added range-over-func iterators, equally single-pass).
Java: Stream.count() is a terminal reduction — the stream is consumed and closed after counting; count again via a fresh data.stream() (s2 in the example); the underlying collection's size() is the O(1), repeatable counterpart — a sharp contrast with PHP's ArrayIterator (current() NULL after walking).
JavaScript: a generator is a one-shot iterator — [...it] consumes it, a second spread yields 0; materialize into an array first for repeatable counting (same trick as Python's list(it)).
Python: len(list(it)) (the example) is the idiom — materialize then count; an exhausted generator lists as empty; sum(1 for _ in it) counts without materializing but consumes the iterator just the same.
Rust: Iterator::count() consumes self — the iterator is moved after one call and a second call will not compile (ownership makes walk-once a compile-time constraint, unique among the ten languages); .len() belongs to the collection itself and is unaffected.
TypeScript: same as JavaScript; Generator<T> typing matches the one-shot runtime semantics — after a spread, length stays 0.
Teaching anchor: counting/traversal consumes streaming data structures — PHP iterator_count, Java Stream.count, Rust Iterator::count, Python and JS generators all behave this way; the exceptions are containers (arrays/collections/Lists) whose size/len/count repeat forever — telling the iterator VIEW from the container itself is the point of this entry.