Arrays\chunk()

transformer lazy accepts iterable returns Closure pure
(int, bool) → (Iterable → Iterable)
At a glance — Batch an iterable into groups of N. Lazy — yields each batch as it's filled. Values below 1 for the size are clamped to 1.

Creates a Closure that splits an array or iterable into batches of up to N elements. The final batch may be smaller if the source size doesn't divide evenly.

/**
  * @param int $count Max size of each chunk.
  * @param bool $preserveKeys Should source keys be kept inside each batch.
  * @return Closure(iterable<int|string, mixed>):(array<int, array<int|string, mixed>>|\Generator<int, array<int|string, mixed>>)
  */
Arrays\chunk(int $count, bool $preserveKeys = false): Closure

Returned Closure

When Arrays\chunk() is called, it returns the following Closure which can be used like a regular function.

/**
  * @param iterable<int|string, mixed> $source
  * @return array<int, array<int|string, mixed>>|\Generator<int, array<int|string, mixed>>
  */
$function (iterable $source): array|\Generator

Examples

Partial Application

This can be used to create a simple closure which can be used as a regular function.

$pairs = Arrays\chunk(2);

print_r($pairs([1, 2, 3, 4, 5]));
// [[1, 2], [3, 4], [5]]

Curried

This can be called inline using currying.

print_r(Arrays\chunk(3)(['a', 'b', 'c', 'd', 'e']));
// [['a', 'b', 'c'], ['d', 'e']]

Details

Arrays Functions

Releated Array manipulation Functions