array_chunk
Splits an array into chunks of a given size.
Syntax
array_chunk(array $array, int $length, bool $preserve_keys = false): arrayParameters
| Parameter | Type | Description |
|---|---|---|
| $array | array | The source array. |
| $length | int | The size of each chunk. |
| $preserve_keys | bool | Optional. `true` keeps the original keys. |
Return value
arrayAn array of arrays.
Examples
Products three per row:
<?php
echo json_encode(array_chunk([1, 2, 3, 4, 5, 6, 7], 3));Output:
[[1,2,3],[4,5,6],[7]]The number of pages:
<?php
$items = range(1, 45);
echo count(array_chunk($items, 10));Output:
5Notes
The last chunk may be shorter than the others.
See also
- array_slice — Returns part of an array.
- str_split — Splits a string into pieces of a given length.
Related recipes
In the tutorial
- Array functions — Processing arrays in PHP without loops — array_map, array_filter, array_reduce, searching and slicing.