Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

array_chunk

Splits an array into chunks of a given size.

Syntax

array_chunk(array $array, int $length, bool $preserve_keys = false): array

Parameters

ParameterTypeDescription
$arrayarrayThe source array.
$lengthintThe size of each chunk.
$preserve_keysboolOptional. `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:

5

Notes

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.

Thanks for reading!

Donate to the site — we work hard for you.