3v4l.org

run code in 300+ PHP versions simultaneously
<?php class myData implements IteratorAggregate { public $property1 = "Public property one"; public $property2 = "Public property two"; public $property3 = "Public property three"; public function getIterator() : ArrayIterator { return new ArrayIterator($this); } } class myIterator implements Iterator { private $position = 0; private $array = ['property1'=>'Public property one', 'property2'=>'Public property two', 'property3'=>'Public property three']; function rewind(): void { $this->position = 0; } function current(): mixed { $position = $this->position + 1; $key = 'property' . $position; return $this->array[$key]; } function key(): mixed { $position = $this->position + 1; $key = 'property' . $position; return $key; } function next(): void { ++$this->position; } function valid(): bool { $position = $this->position + 1; $key = 'property' . $position; return isset($this->array[$key]); } } $renderFunction = function($iterator) { foreach($iterator as $key => $value) { echo "$key: $value\n"; foreach($iterator as $key => $value) { echo " $key: $value\n"; } } }; echo "----- Aggregate Iterator -----\n"; $renderFunction(new myData); echo "\n----- Simple Iterator-----\n"; $renderFunction(new myIterator);
Output for 8.0.1 - 8.0.30, 8.1.0 - 8.1.33, 8.2.0 - 8.2.29, 8.3.0 - 8.3.26, 8.4.1 - 8.4.13
----- Aggregate Iterator ----- property1: Public property one property1: Public property one property2: Public property two property3: Public property three property2: Public property two property1: Public property one property2: Public property two property3: Public property three property3: Public property three property1: Public property one property2: Public property two property3: Public property three ----- Simple Iterator----- property1: Public property one property1: Public property one property2: Public property two property3: Public property three

preferences:
72.57 ms | 408 KiB | 5 Q