PHP
Divide a PHP Array into Chunks
Learn how to efficiently split a large PHP array into smaller, manageable chunks using the array_chunk function for processing or display in web development.
<?php
$items = ['apple', 'banana', 'cherry', 'date', 'elderberry', 'fig', 'grape', 'honeydew'];
$chunks = array_chunk($items, 3);
print_r($chunks);
$itemsWithKeys = [
'a' => 'apple',
'b' => 'banana',
'c' => 'cherry',
'd' => 'date',
'e' => 'elderberry'
];
// Preserve keys (optional, default is false)
$chunksPreservingKeys = array_chunk($itemsWithKeys, 2, true);
print_r($chunksPreservingKeys);
?>
How it works: The `array_chunk()` function splits an array into smaller arrays, or 'chunks'. It takes the input array, the size of each chunk, and an optional boolean parameter to preserve keys. This is particularly useful for pagination, displaying data in grids, or processing large datasets in smaller batches.