Skip to content

Instantly share code, notes, and snippets.

@bricejulia
Created June 12, 2023 16:13
Show Gist options
  • Save bricejulia/05d7a93ad46494ba0af1fc29df556f07 to your computer and use it in GitHub Desktop.
Save bricejulia/05d7a93ad46494ba0af1fc29df556f07 to your computer and use it in GitHub Desktop.
batch function
<?php
function batch(
iterable $items,
callable $exec,
?callable $flush = null,
int $batchSize = 20,
): void
{
$current = 0;
foreach ($items as $item) {
$exec($item);
$current++;
if ($current % $batchSize === 0) {
if ($flush) {
$flush($current);
}
}
}
if ($flush) {
$flush($current);
}
}
batch(
items: [4, 3, 2, 1],
exec: fn(int $item) => var_dump('handling item', $item),
flush: fn(int $index) => var_dump('flush at index', $index),
batchSize: 2
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment