When working with large PHP arrays, you sometimes need to divide the data into smaller groups. For example, you might want to display products in rows, process records in batches, or divide a list of users into manageable sections.
PHP provides the array_chunk() function to split an array into smaller arrays containing a specified number of elements.
In this guide, you'll learn how array_chunk() works, how to preserve array keys, and how to use it in practical situations.
What Is array_chunk() in PHP?
The array_chunk() function divides an array into smaller arrays called chunks.
Its syntax is:
array_chunk(
array $array,
int $length,
bool $preserve_keys = false
): array
The function accepts three parameters:
$array— The original array to split.$length— The maximum number of elements in each chunk.$preserve_keys— Whether to preserve the original array keys. The default isfalse.
The function returns a new multidimensional array containing the smaller arrays.
If the number of elements isn't evenly divisible by the chunk size, the final chunk contains fewer elements.
Example 1: Splitting an Indexed Array
Let's divide a list of six numbers into groups of two.
<?php
$numbers = [10, 20, 30, 40, 50, 60];
$chunks = array_chunk($numbers, 2);
print_r($chunks);
Output:
Array
(
[0] => Array
(
[0] => 10
[1] => 20
)
[1] => Array
(
[0] => 30
[1] => 40
)
[2] => Array
(
[0] => 50
[1] => 60
)
)
PHP creates three smaller arrays, each containing two elements.
You can access an individual chunk using its numeric index:
$firstChunk = $chunks[0];
The original $numbers array remains unchanged.
Example 2: When the Last Chunk Is Smaller
The number of elements doesn't need to divide evenly into the requested chunk size.
<?php
$colors = ["Red", "Green", "Blue", "Yellow", "Purple"];
$chunks = array_chunk($colors, 2);
foreach ($chunks as $chunk) {
echo implode(", ", $chunk) . PHP_EOL;
}
Output:
Red, Green
Blue, Yellow
Purple
The first two chunks contain two elements, while the last contains only one.
PHP doesn't add empty values to fill the final chunk.
Preserving Original Array Keys
By default, array_chunk() assigns new numeric keys to the elements inside each chunk.
This is important when working with associative arrays.
For example:
<?php
$prices = [
"Keyboard" => 50,
"Mouse" => 25,
"Monitor" => 200
];
$chunks = array_chunk($prices, 2, true);
print_r($chunks);
Output:
Array
(
[0] => Array
(
[Keyboard] => 50
[Mouse] => 25
)
[1] => Array
(
[Monitor] => 200
)
)
The third parameter, true, tells PHP to preserve the original keys.
Without it, the product names would be replaced by numeric indexes within each chunk.
Recommendation: Use $preserve_keys = true when the original keys contain meaningful information, such as product IDs or configuration names.
Practical Example: Processing Products in Batches
Imagine an application that needs to process product records in smaller groups.
Instead of processing the entire list as one unit, you can divide it into batches.
Create a file named product-batches.php:
<?php
declare(strict_types=1);
$products = [
["id" => 101, "name" => "Keyboard"],
["id" => 102, "name" => "Mouse"],
["id" => 103, "name" => "Monitor"],
["id" => 104, "name" => "Webcam"],
["id" => 105, "name" => "Headset"]
];
// Divide products into batches of two.
$batches = array_chunk($products, 2);
// Process each batch.
foreach ($batches as $index => $batch) {
echo "<h2>Batch " . ($index + 1) . "</h2>";
echo "<ul>";
foreach ($batch as $product) {
echo "<li>" . htmlspecialchars(
$product["name"],
ENT_QUOTES,
"UTF-8"
) . "</li>";
}
echo "</ul>";
}
Browser output:
Batch 1
- Keyboard
- Mouse
Batch 2
- Monitor
- Webcam
Batch 3
- Headset
The example creates three batches and processes them individually.
This approach is useful when an operation should handle a limited number of records at a time, such as preparing grouped reports or submitting batches to an external service.
Performance note: array_chunk() creates an array containing all the chunks. It does not stream records from a database or file. For extremely large datasets, processing records incrementally may be more memory-efficient.
Handling Empty Arrays and Invalid Chunk Sizes
If you pass an empty array, array_chunk() returns an empty array.
<?php
$result = array_chunk([], 3);
var_dump($result);
Output:
array(0) {
}
The chunk size must be greater than zero.
In PHP 8 and later, passing 0 or a negative number throws a ValueError.
<?php
try {
$chunks = array_chunk([1, 2, 3], 0);
} catch (ValueError $error) {
echo "Chunk size must be greater than zero.";
}
Validate dynamic chunk sizes before calling the function to avoid unnecessary exceptions.
array_chunk() vs array_slice()
Both functions work with portions of arrays, but they serve different purposes.
| Function | Purpose |
|---|---|
array_chunk() |
Splits an entire array into multiple smaller arrays. |
array_slice() |
Extracts a specific section of an array using an offset and optional length. |
Use array_chunk() when you need to divide the complete collection into groups. Use array_slice() when you only need a particular section.
Common Mistakes
- Using a zero or negative chunk size: The length must be at least
1. - Losing meaningful keys: Pass
trueas the third argument to preserve original keys. - Expecting equal-sized chunks: The last chunk may contain fewer elements.
- Expecting a flat array: The result is a multidimensional array.
- Assuming chunking reduces memory usage: All chunks are returned together, so the operation does not provide streaming.
Key Takeaways
array_chunk()divides an array into smaller arrays.- The second parameter controls the maximum number of elements per chunk.
- The final chunk may contain fewer elements.
- Use the third parameter to preserve original array keys.
- The function returns an empty array when the input array is empty.
- Invalid chunk sizes throw a
ValueErrorin PHP 8+. - Chunking is useful for grouping records and processing data in batches.
The array_chunk() function provides a simple way to organize PHP arrays into manageable groups. Whether you're displaying records in sections or preparing data for batch operations, it helps keep your processing logic clear and predictable.
For additional details, see the official PHP array_chunk() documentation.