Laravel Collection Public API: chunk

November 29, 2016 —John Koster

chunk($size, $preserveKeys = false)

The chunk method is useful when working with large collections in that it allows developers to create smaller collections to work with. The chunk method defines two parameters: $size, which is used to control how large each newly created collection will be; and $preserveKeys, which indicates if the chunk method will preserve array keys when creating the new collections.

Assuming the following code:

1<?php
2 
3$testArray = [
4 'one' => '1',
5 'two' => '2',
6 'three' => '3',
7 'four' => '4',
8 'five' => '5',
9 'six' => '6'
10];
11 
12$collection = new Collection($testArray);
13 
14$chunks = $collection->chunk(3);

The $chunks variable will contain a value similar to the following:

1object(Illuminate\Support\Collection)[135]
2 protected 'items' =>
3 array (size=2)
4 0 =>
5 object(Illuminate\Support\Collection)[133]
6 protected 'items' =>
7 array (size=3)
8 0 => string '1' (length=1)
9 1 => string '2' (length=1)
10 2 => string '3' (length=1)
11 1 =>
12 object(Illuminate\Support\Collection)[134]
13 protected 'items' =>
14 array (size=3)
15 0 => string '4' (length=1)
16 1 => string '5' (length=1)
17 2 => string '6' (length=1)

As you can see, the chunk method returned a new collection that contains two new collections, each containing three elements. It should also be noted that the original array keys are missing (there are no numerical word names). This can be changed by passing true as the second argument:

1<?php
2 
3$chunks = $collection->chunk(3, true);

Now the $chunks variable would have a value similar to the following:

1object(Illuminate\Support\Collection)[135]
2 protected 'items' =>
3 array (size=2)
4 0 =>
5 object(Illuminate\Support\Collection)[133]
6 protected 'items' =>
7 array (size=3)
8 'one' => string '1' (length=1)
9 'two' => string '2' (length=1)
10 'three' => string '3' (length=1)
11 1 =>
12 object(Illuminate\Support\Collection)[134]
13 protected 'items' =>
14 array (size=3)
15 'four' => string '4' (length=1)
16 'five' => string '5' (length=1)
17 'six' => string '6' (length=1)

The resulting collections now have the original array keys.

Some absolutely amazing
people

The following amazing people help support this site and my open source projects ♥️
If you're interesting in supporting my work and want to show up on this list, check out my GitHub Sponsors Profile.