The Power of PHP's array_chunk Function
The PHP programming language has a vast collection of built-in functions, each designed to make developers' lives easier. One such function is array_chunk, a
PHP has a large collection of built-in array functions, and array_chunk() is one of the most useful for working with large data sets. It splits a single array into a series of smaller arrays ("chunks") of a fixed size, which makes data easier to paginate, batch, and lay out. This chapter explains the syntax, walks through runnable examples, covers the preserve_keys flag, and points out the common gotchas.
What is the array_chunk Function?
The array_chunk() function splits an array into smaller arrays, each containing a specified number of elements. It is useful whenever you need to break a long list into evenly sized groups — for example, rendering a grid of N columns, processing records in batches, or building paginated output.
Syntax
array_chunk(array $array, int $length, bool $preserve_keys = false): array| Parameter | Description |
|---|---|
$array | The array to split. |
$length | The size of each chunk. Must be 1 or greater, or array_chunk() throws a ValueError (PHP 8+) / emits a warning (PHP 7). |
$preserve_keys | Optional. false (default) reindexes each chunk from 0; true keeps the original keys. |
Return value: a new multidimensional array. The original array is never modified — array_chunk() does not work in place.
How does array_chunk Work?
array_chunk() walks the input array in order and copies elements into a fresh sub-array until it reaches $length elements, then starts a new chunk. The final chunk holds whatever is left over, so it may be smaller than the others.
By default the third parameter, preserve_keys, is false, which reindexes the keys in each chunk starting from 0. Setting it to true preserves the original array keys — important when those keys carry meaning (such as string keys or non-sequential IDs).
For example, consider the following array:
PHP define an array
If we call array_chunk on this array, passing in a value of 3 for the second argument, we get the following result:
Array
(
[0] => Array
(
[0] => a
[1] => b
[2] => c
)
[1] => Array
(
[0] => d
[1] => e
[2] => f
)
[2] => Array
(
[0] => g
)
)As you can see, the original array has been divided into three smaller arrays, each containing three elements (with the exception of the final array, which contains only one).
Preserving Original Keys
By default, each chunk is reindexed from 0. Pass true as the third argument to keep the original keys instead:
<?php
$data = array("id10" => "a", "id20" => "b", "id30" => "c");
print_r(array_chunk($data, 2, true));
?>Output:
Array
(
[0] => Array
(
[id10] => a
[id20] => b
)
[1] => Array
(
[id30] => c
)
)Keep preserve_keys set to true whenever the keys identify the data (string keys, database IDs, etc.); otherwise they are lost on the next reindex.
Why Use array_chunk?
The array_chunk function is incredibly useful for a variety of applications, including:
- Breaking down large arrays into smaller, more manageable parts for processing.
- Displaying large amounts of data in a paginated manner (e.g. splitting an array of results into smaller arrays for display on multiple pages).
- Improving the performance of algorithms that operate on arrays by reducing the size of arrays being processed at any given time.
Example Use Case: Pagination
One of the most common use cases for the array_chunk function is pagination. Consider the following example, where we have an array of 12 results that we want to display on 2 pages:
Example of php array_chunk function
array_chunk() divides the 12 results into 2 pages: the first chunk holds 10 elements and the second holds the remaining 2. Each chunk maps directly to a page, so you can render $pages[0] for page 1, $pages[1] for page 2, and use count($pages) to build the page links.
Common Gotchas
$lengthmust be at least 1. A value of0or a negative number throws aValueErrorin PHP 8 and raised a warning in PHP 7.- The original array is untouched.
array_chunk()returns a new array; assign the result, don't expect it to mutate the input. - Order is preserved, keys are not (by default). Elements stay in their original order, but numeric keys are reset to
0..nunless you passpreserve_keys = true. - The last chunk can be shorter. Always handle a final chunk smaller than
$lengthwhen looping.
Related Functions
- array_slice() — extract a single contiguous portion of an array instead of splitting the whole thing.
- array_splice() — remove or replace a portion of an array in place.
- array_merge() — combine several arrays back into one.
- array_map() — apply a callback to each chunk after splitting.
- PHP Arrays — a refresher on indexed and associative arrays.
Conclusion
The array_chunk() function is a simple, effective way to divide a large array into smaller, evenly sized parts. Whether you are paginating results, batching records for processing, or laying out a grid, it keeps array handling readable and predictable. Remember the two rules that trip people up: the chunk size must be at least 1, and keys are reindexed unless you ask to preserve them.