Syntax
array_chunk($items, $batchSize, preserve_keys: true)Examples
PHP array_chunk batches
Run as a PHP 8.0+ CLI script, for example php example.php. The multibyte example additionally requires mbstring.
<?php
$jobs = ['a' => 10, 'b' => 20, 'c' => 30];
foreach (array_chunk($jobs, 2, true) as $batch) {
echo implode(',', array_keys($batch)), PHP_EOL;
}- Output: a,b on the first line and c on the second. The original keys identify work within each batch.
Best practices
- Require a positive batch size. Chunking an already-materialized array does not make an unbounded data source memory-efficient.
Runtime & versions
PHP runtime on a server or CLI. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
PHP Manual