CKTIS / PHP
Iterator
Define a cursor using rewind, valid, current, key and next. foreach rewinds at the start, checks valid before reading and advances after each element. valid must track position independently of the current value so a stored null or false does not terminate traversal.
Version: PHP 8.4; repository runtime, production runtime not attested
Syntax
class Steps implements IteratorDefine a cursor using rewind, valid, current, key and next. foreach rewinds at the start, checks valid before reading and advances after each element. valid must track position independently of the current value so a stored null or false does not terminate traversal. The Iterator::current method returns the value at the current position and Iterator::key returns its key. In this cursor Iterator::rewind resets the position to zero, Iterator::valid checks that the index exists, and Iterator::next advances by one.
class Steps implements Iterator { private int $i=0; private array $v=[null,false,3]; public function rewind():void{$this->i=0;} public function valid():bool{return array_key_exists($this->i,$this->v);} public function current():mixed{return $this->v[$this->i];} public function key():int{return $this->i;} public function next():void{++$this->i;} }
echo json_encode(iterator_to_array(new Steps()));
[null,false,3]
Examples
<?php
class Steps implements Iterator { private int $i=0; private array $v=[null,false,3]; public function rewind():void{$this->i=0;} public function valid():bool{return array_key_exists($this->i,$this->v);} public function current():mixed{return $this->v[$this->i];} public function key():int{return $this->i;} public function next():void{++$this->i;} }
echo json_encode(iterator_to_array(new Steps()));
Result
[null,false,3]