Laravel Collection Public API: every

November 30, 2016 —John Koster

every($step, $offset = 0)

The every method can be used to retrieve a subset of a collection based on each items distance from each other. It defines one required parameter $step and one optional parameter $offset.

An argument supplied for $step determines how far each item must be from each other in order to be included in the final collection. In other words, the $step is used to say "get every N-th item, where N is the $step.

An argument supplied for $offset (which is 0 by default) determines where to start when building the final collection.

The following example creates a simple collection populated with the range of numbers from 0 to 10 (there will be eleven items in the collection):

1<?php
2 
3// Create a new collection.
4$collection = collect(range(0,10));

We can retrieve all the even numbers using the every method like so:

1<?php
2 
3// Retrieve the even numbers.
4$evenNumbers = $collection->every(2);

After the code has executed, the $evenNumbers variable will hold a value similar to the following output:

1Collection {
2 #items: array:6 [
3 0 => 0
4 1 => 2
5 2 => 4
6 3 => 6
7 4 => 8
8 5 => 10
9 ]
10}

As we can see, the returned collection contains all the even numbers from the original collection. Conversely, we can retrieve all the odd numbers just as easily:

1<?php
2 
3// Retrieve the odd numbers.
4$oddNumbers = $collection->every(2,1);

It should be noted that we had to supply an argument for the $offset parameter. So the meaning of our method call could be interpreted as "get every second item starting with the item at index 1". After the above example has executed, the $oddNumbers variable will hold a value similar to the following output:

1Collection {
2 #items: array:5 [
3 0 => 1
4 1 => 3
5 2 => 5
6 3 => 7
7 4 => 9
8 ]
9}

Here is another simple example that returns every 50th item from a collection of numbers ranging from 0 to 1000:

1<?php
2 
3// Create a new collection with a range
4// of numbers.
5$collection = collect(range(0,1000));
6 
7// Generate a subset of the collection.
8$subset = $collection->every(50);

After the code has executed, $subset would contain a value similar to the following output:

1Collection {
2 #items: array:21 [
3 0 => 0
4 1 => 50
5 2 => 100
6 3 => 150
7 4 => 200
8 5 => 250
9 6 => 300
10 7 => 350
11 8 => 400
12 9 => 450
13 10 => 500
14 11 => 550
15 12 => 600
16 13 => 650
17 14 => 700
18 15 => 750
19 16 => 800
20 17 => 850
21 18 => 900
22 19 => 950
23 20 => 1000
24 ]
25}

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.