← Back to all snippets
PHP

Splitting an Array into Chunks

Learn how to divide a large PHP array into smaller, manageable chunks (sub-arrays) of a specified size, which is perfect for pagination or processing data in batches.

<?php
$items = ['item1', 'item2', 'item3', 'item4', 'item5', 'item6', 'item7', 'item8', 'item9', 'item10'];

// Split into chunks of 3
$chunksOf3 = array_chunk($items, 3);
echo "Chunks of 3:
";
print_r($chunksOf3);

// Split into chunks of 4, preserving keys
$associativeItems = [
    'a' => 'apple', 'b' => 'banana', 'c' => 'cherry',
    'd' => 'date', 'e' => 'elderberry', 'f' => 'fig'
];
$chunksOf4PreserveKeys = array_chunk($associativeItems, 4, true);
echo "
Chunks of 4 (preserving keys):
";
print_r($chunksOf4PreserveKeys);

// Split into chunks of 4, keys reset
$chunksOf4ResetKeys = array_chunk($associativeItems, 4, false);
echo "
Chunks of 4 (keys reset):
";
print_r($chunksOf4ResetKeys);
?>
How it works: The array_chunk() function splits an array into new arrays, each containing a specified number of elements. This is highly useful for pagination (e.g., displaying 10 items per page), rendering data in grid-like layouts, or processing large datasets in smaller, more manageable batches to optimize memory usage. The optional third argument allows you to preserve the original keys from the input array; otherwise, the new chunks will be re-indexed numerically from zero.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs