Search

Laravel 5 Collections: Splitting a Collection Into Smaller Pieces With chunk

April 22, 2018 —John Koster

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.

#Signature

1public function chunk(
2 $size
3);

#Example Use

Assuming the following example code:

{lang="php",line-numbers=on}

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

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

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

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$chunks = $collection->chunk(3, true);

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

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

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.