PHP split an iterable into fixed-size chunks
PHP
<?php
function chunk_iterable(iterable $items, int $size): Generator
{
if ($size < 1) {
throw new InvalidArgumentException('Chunk size must be at least 1');
}
$batch = [];
foreach ($items as $item) {
$batch[] = $item;
if (count($batch) === $size) {
yield $batch;
$batch = [];
}
}
if ($batch !== []) {
yield $batch;
}
}