01 · THE IDEAREAD → TRY → LEARN
Why batch data?
Programs often have more items than they should handle at once. You might send 100 emails per request, insert 500 rows per query, or show 20 results per page. In each case you split one long list into smaller groups, called chunks or batches. PHP has a built-in function for this: array_chunk().
The signature
array_chunk(array $array, int $length, bool $preserve_keys = false): array
It takes an array and a chunk size, and returns a new array whose elements are the chunks. Every chunk has exactly length elements except possibly the last one, which holds whatever is left over. The outer array is numerically indexed from zero.
A first example
Five letters split into chunks of two give three chunks: two full ones and a final chunk with a single item.
$items = ['a', 'b', 'c', 'd', 'e'];
echo json_encode(array_chunk($items, 2), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), "\n";[["a","b"],["c","d"],["e"]]
The last chunk is shorter. Never write code that assumes every batch is full.
What happens to keys?
By default each chunk is re-indexed from zero. If the original keys matter, for example record IDs, pass true as the third argument and each element keeps its key.
$items = ['a', 'b', 'c', 'd', 'e'];
echo json_encode(array_chunk($items, 2, true), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), "\n";[["a","b"],{"2":"c","3":"d"},{"4":"e"}]
Look at the JSON. The first chunk has keys 0 and 1, so it still looks like a list. The later chunks start at 2 and 4, so json_encode() writes them as objects. The data is the same either way, but the key choice changes the shape.
Empty input and invalid sizes
Two edge cases deserve attention:
- An empty array produces an empty array of chunks,
[]. There is no empty chunk inside it. - A length below 1 is an error. Since PHP 8.0,
array_chunk()throws aValueErrorfor a length of 0 or less. Older versions raised a warning and returnednull.
If the size comes from user input or configuration, validate it before calling the function. You can either let the exception happen or choose a safe fallback. Which is better depends on the program: a fallback hides mistakes, while an exception exposes them.
Worked example: summing each batch
Now combine chunking with a small function. batch_sums() splits numbers into groups and returns the total of each group. It guards the size and returns an empty list for bad sizes.
function batch_sums(array $numbers, int $size): array {
if ($size < 1) {
return [];
}
$sums = [];
foreach (array_chunk($numbers, $size) as $chunk) {
$sums[] = array_sum($chunk);
}
return $sums;
}
echo json_encode(batch_sums([1, 2, 3, 4, 5], 2)), "\n";
echo json_encode(batch_sums([], 3)), "\n";
echo json_encode(batch_sums([1, 2], 0)), "\n";[3,7,5] [] []
The numbers 1 to 5 in pairs give [1,2], [3,4] and [5], so the sums are 3, 7 and 5. The guard comes first so the invalid size never reaches array_chunk().
Common mistakes
- Assuming equal sizes. The final chunk can be smaller, so do not index into it blindly.
- Forgetting the size check. A size of 0 causes a
ValueErrorin PHP 8.4. - Dropping the remainder. A hand-written loop that only keeps full groups silently loses data.
- Expecting original keys. Without
preserve_keys, keys are reset in every chunk.
Exercise contract
Write a function named make_batches(array $items, int $size): array.
- Return a list of batches, each holding at most
$sizeitems in the original order. - Keep the leftover items as a shorter final batch.
- Return
[]for an empty input array. - Return
[]when$sizeis less than 1 instead of throwing.
The tests compare the returned arrays, so just return the value and do not print anything. You can solve it with array_chunk() plus one guard, or write the loop yourself with array_slice(). Either way, check that the last partial batch survives.
Recap
array_chunk() splits an array into groups of a fixed size, keeps order, re-indexes each chunk unless asked otherwise, and leaves a shorter last chunk. Empty input gives an empty result, and a length below 1 throws a ValueError. Guard the size when it comes from outside your code.
Functions · Arrays · Types
- Split arrays into bounded groups and handle empty input
- Implement and test a deterministic PHP 8.4 function