PHP
Split a Large Array into Smaller Chunks
Learn how to easily divide a large PHP array into multiple smaller arrays of a specified size using `array_chunk`, ideal for pagination, batch processing, or UI display.
<?php
$items = range(1, 15); // Create an array with numbers 1 to 15
$chunkSize = 4;
$chunks = array_chunk($items, $chunkSize);
echo "Original array:
";
print_r($items);
echo "
Array split into chunks of {$chunkSize}:
";
print_r($chunks);
// Output for Original array:
// Array
// (
// [0] => 1
// [1] => 2
// [2] => 3
// [3] => 4
// [4] => 5
// [5] => 6
// [6] => 7
// [7] => 8
// [8] => 9
// [9] => 10
// [10] => 11
// [11] => 12
// [12] => 13
// [13] => 14
// [14] => 15
// )
// Output for Array split into chunks of 4:
// Array
// (
// [0] => Array
// (
// [0] => 1
// [1] => 2
// [2] => 3
// [3] => 4
// )
// [1] => Array
// (
// [0] => 5
// [1] => 6
// [2] => 7
// [3] => 8
// )
// [2] => Array
// (
// [0] => 9
// [1] => 10
// [2] => 11
// [3] => 12
// )
// [3] => Array
// (
// [0] => 13
// [1] => 14
// [2] => 15
// )
// )
?>
How it works: `array_chunk()` is a simple yet powerful function for dividing a large array into smaller, more manageable pieces. You provide the original array and the desired size for each chunk. The function returns a new multidimensional array, where each inner array represents a chunk. This is incredibly useful for implementing pagination logic, processing data in batches to avoid memory issues, or displaying items in a grid layout where each row contains a fixed number of elements.