CKTIS / PHP
IteratorIterator
Adapt a Traversable source to the Iterator cursor interface.
Version: PHP 8.4; repository runtime, production runtime not attested
Syntax
new IteratorIterator($traversable)Adapt a Traversable source to the Iterator cursor interface. This is useful when code receives an IteratorAggregate but needs current, next and key. Rewind the wrapper before reading it manually. The wrapped data is traversed without eagerly copying it into an array.
class Source implements IteratorAggregate { public function getIterator(): Traversable {yield "x"=>4;yield "y"=>8;} }
$it=new IteratorIterator(new Source()); $it->rewind(); $first=$it->key(); $it->next(); echo json_encode([$first,$it->key(),$it->current()]);
["x","y",8]
Examples
<?php
class Source implements IteratorAggregate { public function getIterator(): Traversable {yield "x"=>4;yield "y"=>8;} }
$it=new IteratorIterator(new Source()); $it->rewind(); $first=$it->key(); $it->next(); echo json_encode([$first,$it->key(),$it->current()]);
Result
["x","y",8]