PHP
Split an Array into Chunks for Pagination or Batch Processing
Learn to divide a large PHP array into smaller, manageable chunks of a specified size, perfect for pagination, batch updates, or displaying data in segmented views.
<?php
$large_dataset = [];
for ($i = 1; $i <= 25; $i++) {
$large_dataset[] = "Item " . $i;
}
echo "Original dataset (25 items):
";
print_r($large_dataset);
$chunk_size = 5;
$chunks = array_chunk($large_dataset, $chunk_size);
echo "
Dataset chunked into arrays of size {$chunk_size}:
";
print_r($chunks);
echo "
Iterating through chunks for pagination example:
";
foreach ($chunks as $page_number => $page_items) {
echo "--- Page " . ($page_number + 1) . " ---
";
foreach ($page_items as $item) {
echo "- " . $item . "
";
}
}
// Example with preserving keys
$assoc_data = ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5, 'f' => 6];
$chunks_with_keys = array_chunk($assoc_data, 2, true);
echo "
Associative array chunked (preserving keys):
";
print_r($chunks_with_keys);
?>
How it works: The `array_chunk()` function is a powerful PHP tool for breaking down a single array into multiple smaller arrays, each containing a specified number of elements. This is incredibly useful for tasks like pagination, where you need to display a subset of data on each page, or for batch processing, where you process data in smaller, more manageable blocks. The third optional parameter allows you to preserve the original keys.