3v4l.org

run code in 300+ PHP versions simultaneously
<?php function chunk_iterator(Iterator $it, int $n) { $chunk = []; for($i = 0; $it->valid(); $i++){ $chunk[] = $it->current(); $it->next(); if(count($chunk) == $n){ yield $chunk; $chunk = []; } } if(count($chunk)){ yield $chunk; } } // For demonstration, create an iterator from array $arr = range(20, 40, 1); $it = new ArrayIterator($arr); // Iterate over the generator foreach(chunk_iterator($it, 6) as $c){ echo implode(',', $c)."\n"; }

preferences:
43.58 ms | 402 KiB | 5 Q