Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access the nth item in a Laravel collection?

Tags:

I guess I am breaking all the rules by deliberately making a duplicate question...

The other question has an accepted answer. It obviously solved the askers problem, but it did not answer the title question.

Let's start from the beginning - the first() method is implemented approximately like this:

foreach ($collection as $item)     return $item; 

It is obviously more robust than taking $collection[0] or using other suggested methods.

There might be no item with index 0 or index 15 even if there are 20 items in the collection. To illustrate the problem, let's take this collection out of the docs:

$collection = collect([     ['product_id' => 'prod-100', 'name' => 'desk'],     ['product_id' => 'prod-200', 'name' => 'chair'], ]);  $keyed = $collection->keyBy('product_id'); 

Now, do we have any reliable (and preferably concise) way to access nth item of $keyed?

My own suggestion would be to do:

$nth = $keyed->take($n)->last(); 

But this will give the wrong item ($keyed->last()) whenever $n > $keyed->count(). How can we get the nth item if it exists and null if it doesn't just like first() behaves?

Edit

To clarify, let's consider this collection:

$col = collect([     2 => 'a',     5 => 'b',     6 => 'c',     7 => 'd']); 

First item is $col->first(). How to get the second?

$col->nth(3) should return 'c' (or 'c' if 0-based, but that would be inconsistent with first()). $col[3] wouldn't work, it would just return an error.

$col->nth(7) should return null because there is no seventh item, there are only four of them. $col[7] wouldn't work, it would just return 'd'.

You could rephrase the question as "How to get nth item in the foreach order?" if it's more clear for some.

like image 786
Džuris Avatar asked Nov 06 '16 00:11

Džuris


Video Answer


1 Answers

I guess faster and more memory-efficient way is to use slice() method:

$collection->slice($n, 1); 
like image 99
Alexey Mezenin Avatar answered Oct 25 '22 15:10

Alexey Mezenin