PHP
Split Array into Smaller Chunks
Discover how to divide a large PHP array into multiple smaller arrays (chunks) of a specified size, useful for pagination or batch processing.
<?php
$products = [
'Laptop', 'Mouse', 'Keyboard', 'Monitor', 'Webcam',
'Headphones', 'Speaker', 'Microphone', 'Router', 'Printer',
'SSD', 'HDD', 'GPU', 'CPU', 'RAM'
];
$chunkSize = 3;
$productChunks = array_chunk($products, $chunkSize);
// Iterating through chunks for display or processing
foreach ($productChunks as $index => $chunk) {
// echo "Chunk " . ($index + 1) . ": " . implode(', ', $chunk) . "
";
}
/*
Expected output for $productChunks:
Array (
[0] => Array ([0] => Laptop [1] => Mouse [2] => Keyboard)
[1] => Array ([0] => Monitor [1] => Webcam [2] => Headphones)
[2] => Array ([0] => Speaker [1] => Microphone [2] => Router)
[3] => Array ([0] => Printer [1] => SSD [2] => HDD)
[4] => Array ([0] => GPU [1] => CPU [2] => RAM)
)
*/
// Example with preserving keys
$users = [
101 => 'Alice',
102 => 'Bob',
105 => 'Charlie',
108 => 'David',
110 => 'Eve',
];
$userChunks = array_chunk($users, 2, true); // true to preserve keys
// var_dump($userChunks);
/*
Expected $userChunks output:
Array (
[0] => Array ([101] => Alice [102] => Bob)
[1] => Array ([105] => Charlie [108] => David)
[2] => Array ([110] => Eve)
)
*/
How it works: The `array_chunk()` function in PHP allows you to split a single array into multiple smaller arrays, or "chunks," each containing a specified number of elements. This is incredibly useful for tasks like pagination, displaying data in columns, or processing large datasets in manageable batches. The third optional parameter, `preserve_keys`, determines whether the original array keys should be maintained in the chunks or if new numeric keys should be assigned.