PHP
Divide an Array into Chunks
Learn to split a PHP array into smaller, manageable chunks of a specified size, perfect for pagination, batch processing, or displaying data in columns.
<?php
$items = ['item1', 'item2', 'item3', 'item4', 'item5', 'item6', 'item7', 'item8', 'item9', 'item10'];
// Chunk the array into groups of 3
$chunks = array_chunk($items, 3);
echo "
Array chunks of size 3:
";
print_r($chunks);
// Chunk the array into groups of 4, preserving keys
$chunksWithKeys = array_chunk($items, 4, true);
echo "
Array chunks of size 4 (preserving keys):
";
print_r($chunksWithKeys);
$dataForProcessing = [
['id' => 1, 'status' => 'new'],
['id' => 2, 'status' => 'new'],
['id' => 3, 'status' => 'pending'],
['id' => 4, 'status' => 'new'],
['id' => 5, 'status' => 'pending'],
['id' => 6, 'status' => 'done']
];
$batchSize = 2;
$batches = array_chunk($dataForProcessing, $batchSize);
echo "
Batches for processing (size $batchSize):
";
foreach ($batches as $index => $batch) {
echo "Batch " . ($index + 1) . ":
";
print_r($batch);
}
/*
Output:
Array chunks of size 3:
Array
(
[0] => Array
(
[0] => item1
[1] => item2
[2] => item3
)
[1] => Array
(
[0] => item4
[1] => item5
[2] => item6
)
[2] => Array
(
[0] => item7
[1] => item8
[2] => item9
)
[3] => Array
(
[0] => item10
)
)
Array chunks of size 4 (preserving keys):
Array
(
[0] => Array
(
[0] => item1
[1] => item2
[2] => item3
[3] => item4
)
[1] => Array
(
[4] => item5
[5] => item6
[6] => item7
[7] => item8
)
[2] => Array
(
[8] => item9
[9] => item10
)
)
Batches for processing (size 2):
Batch 1:
Array
(
[0] => Array
(
[id] => 1
[status] => new
)
[1] => Array
(
[id] => 2
[status] => new
)
)
Batch 2:
Array
(
[0] => Array
(
[id] => 3
[status] => pending
)
[1] => Array
(
[id] => 4
[status] => new
)
)
Batch 3:
Array
(
[0] => Array
(
[id] => 5
[status] => pending
)
[1] => Array
(
[id] => 6
[status] => done
)
)
*/
?>
How it works: The `array_chunk()` function in PHP is used to split an array into smaller, equally sized chunks. It takes the input array, the desired chunk size, and an optional boolean parameter (`preserve_keys`) to specify whether the original keys should be preserved. This is highly useful for pagination (displaying a large dataset in smaller pages), processing data in batches (e.g., sending emails to groups of users), or simply organizing data for display in a grid format.