- implode: documentation ( source)
- range: documentation ( source)
<?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";
}