array_chunk
PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8
The array_chunk function divides an array into multiple array chunks, each containing a specified number of elements. This function is often used to split large datasets into smaller parts for easier processing or paging.
<span class="fun">array_chunk(array $array, int $length, bool $preserve_keys = false): array</span>
Returns a multidimensional array where each element is an array block of length $length . The length of the last block may be less than the specified length.
$input = ['a', 'b', 'c', 'd', 'e']; $result = array_chunk($input, 2); print_r($result);
[Explanation of sample code]$input = ['a', 'b', 'c', 'd', 'e']; $result = array_chunk($input, 2); print_r($result);
In this example, the original array contains 5 elements, which are divided by array_chunk into multiple array chunks of 2 elements per set. The result is a multidimensional array containing 3 subarrays, namely:
Because the $preserve_keys parameter is not set or set to false , the key name is re-indexed to numeric keys starting with 0.