← All languages
PHP function of the day
Random

array_chunk

Split an array into chunks of a specified size.

Description

The array_chunk() function splits an array into arrays of the given size. The last chunk may contain fewer elements if the array cannot be divided evenly.

When preserve_keys is set to true, the original keys are preserved in each chunk. By default, keys are re-indexed numerically starting from zero in each chunk.

This function is useful for paginating data, processing items in batches, or splitting data into groups for display purposes.

Arguments

NameDescriptionOptional
array The array to split. No
length The size of each chunk. No
preserve_keys Whether to preserve original keys. Yes

Example

$data = [1, 2, 3, 4, 5];
$chunks = array_chunk($data, 2);
// [[1, 2], [3, 4], [5]]

Reference