Search

Laravel 5 Collections: Retrieving Collection Elements At a Specific Interval With nth

April 22, 2018 —John Koster

The nth method returns a new collection containing the elements of the original collection that appear at the $step interval (for example, give me every third element within the collection). An $offset may also be specified to indicate which index should be used as the start.

If a value of 1 is supplied as the $step and a value of 0 is supplied as the $offset, the original collection will be returned.

#Signature

1public function nth(
2 $step,
3 $offset = 0
4);

#Example Use

The following examples will use the nth method and PHP's range function to get both the even and odd numbers between 1 and 10.

1// Retrieve the odd numbers.
2$oddNumbers = collect(range(1, 10))->nth(2);
3 
4// Retrieve the even numbers.
5$evenNumbers = collect(range(1, 10))->nth(2, 1);

After the above code has executed, the local variables would contain the following values:

$oddNumbers Values:

Index Value
0 1
1 3
2 5
3 7
4 9

$evenNumbers Values:

Index Value
0 2
1 4
2 6
3 8
4 10

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.