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<?php2 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<?php2 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<?php2 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 => 14 1 => 35 2 => 56 3 => 77 4 => 98 ]9}
Here is another simple example that returns every 50th item from a collection of numbers ranging from 0
to 1000
:
1<?php2 3// Create a new collection with a range4// 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 => 30010 7 => 35011 8 => 40012 9 => 45013 10 => 50014 11 => 55015 12 => 60016 13 => 65017 14 => 70018 15 => 75019 16 => 80020 17 => 85021 18 => 90022 19 => 95023 20 => 100024 ]25}
∎
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.