CKTIS / PHP
Iterators and generators
An iterable may be an array or a Traversable object.
Version: PHP 8.4; repository runtime, production runtime not attested
Syntax
function values(): Generator { yield 2; }An iterable may be an array or a Traversable object. A generator is a stateful iterator that produces values lazily and is not generally rewindable after advancement. Once closed it cannot be traversed a second time. Calling its generator function again creates a fresh independent iterator.
function values(){yield 2;yield 4;} $it=values();$first=iterator_to_array($it);
try{iterator_to_array($it);}catch(Exception $e){$closed=get_class($e);}echo json_encode([$first,$closed,iterator_to_array(values())]);
[[2,4],"Exception",[2,4]]
Examples
<?php
function values(){yield 2;yield 4;} $it=values();$first=iterator_to_array($it);
try{iterator_to_array($it);}catch(Exception $e){$closed=get_class($e);}echo json_encode([$first,$closed,iterator_to_array(values())]);
Result
[[2,4],"Exception",[2,4]]