CKTIS / PHP
iterator_apply()
Invoke a callback while advancing a traversable object.
Version: PHP 8.4; repository runtime, production runtime not attested
Syntax
iterator_apply(Traversable $iterator, callable $callback, ?array $args = null): intInvoke a callback while advancing a traversable object. The current value is not supplied automatically; pass the iterator explicitly in args or capture it. Return true to continue and false to stop. The number of callback invocations includes the one that stops traversal.
Signature
iterator_apply(Traversable $iterator, callable $callback, ?array $args = null): int
Example output
[2,[2,4]]
Examples
<?php
$it = new ArrayIterator([2,4,6]); $seen = [];
$count = iterator_apply($it, function($cursor) use (&$seen) { $seen[] = $cursor->current(); return $cursor->current() < 4; }, [$it]);
echo json_encode([$count,$seen]);
Result
[2,[2,4]]