PHP
Splitting Arrays into Chunks with array_chunk()
Learn to divide a large PHP array into smaller, manageable chunks of a specified size using `array_chunk()`, useful for pagination or batch processing in memory.
<?php
$data = range('a', 'z'); // Create an array from 'a' to 'z'
// Split the array into chunks of 5 elements
$chunks = array_chunk($data, 5);
print_r($chunks);
echo "
";
$items = [
'apple' => 1,
'banana' => 2,
'cherry' => 3,
'date' => 4,
'elderberry' => 5,
];
// Split preserving keys
$chunksPreservingKeys = array_chunk($items, 2, true);
print_r($chunksPreservingKeys);
?>
How it works: The `array_chunk()` function breaks an array into smaller arrays (chunks) of a specified size. This is particularly useful for tasks like displaying results in pages, processing items in batches, or creating sub-groups from a larger dataset already loaded into memory. The optional `preserve_keys` parameter allows you to maintain the original array keys within each chunk.