How to access the nth item in a Laravel collection? -
i guess breaking rules deliberately making duplicate question...
the other question has accepted answer. solved askers problem, did not answer title question.
let's start beginning - first()
method implemented approximately this:
foreach ($collection $item) return $item;
it more robust taking $collection[0]
or using other suggested methods.
there might no item index 0
or index 15
if there 20 items in collection. illustrate problem, let's take collection out of docs:
$collection = collect([ ['product_id' => 'prod-100', 'name' => 'desk'], ['product_id' => 'prod-200', 'name' => 'chair'], ]); $keyed = $collection->keyby('product_id');
now, have reliable (and preferably concise) way access nth item of $keyed
?
my own suggestion do:
$nth = $keyed->take($n)->last();
but give wrong item ($keyed->last()
) whenever $n > $keyed->count()
. how can nth item if exists , null
if doesn't first()
behaves?
edit
to clarify, let's consider collection:
$col = collect([ 2 => 'a', 5 => 'b', 6 => 'c', 7 => 'd']);
first item $col->first()
. how second?
$col->nth(3)
should return 'c'
(or 'c'
if 0-based, inconsistent first()
). $col[3]
wouldn't work, return error.
$col->nth(7)
should return null
because there no seventh item, there 4 of them. $col[7]
wouldn't work, return 'd'
.
you rephrase question "how nth item in foreach order?" if it's more clear some.
i guess faster , more memory-efficient way use slice()
method:
$collection->slice($n, 1);
Comments
Post a Comment