How to access the nth item in a Laravel collection?
I guess faster and more memory-efficient way is to use slice()
method:
$collection->slice($n, 1);
You can try it using values()
function as:
$collection->values()->get($n);
Based on Alexey's answer, you can create a macro in AppServiceProvider (add it inside register method):
use Illuminate\Support\Collection;
Collection::macro('getNth', function ($n) {
return $this->slice($n, 1)->first();
});
and then, you can use this throughout your application:
$collection = ['apple', 'orange'];
$collection->getNth(0) // returns 'apple'
$collection->getNth(1) // returns 'orange'
$collection->getNth(2) // returns null
$collection->getNth(3) // returns null
you may use offsetGet
since Collection
class implements ArrayAccess
$lines->offsetGet($nth);