1
1

More than 1 year has passed since last update.

【Laravel】イミュータブルにCollectionのN番目の要素を取り出す

Last updated at Posted at 2023-01-26

ゴール

  • 元のCollectionの値を変えずにCollectionのN番目の要素を取得する
  • Undifined Index, Undifined Offsetを発生させない

以下5番目の値を取得する場合の方法を記載する

方法1

OK1
$item = $collection->values()->get(4);

get()の引数はindexで指定する。

方法2

OK2
$item = $collection->skip(4)->first();

skip($n)$n個分先頭から要素を削除した新しいcollectionを作成する。

方法3

OK3
$collection->slice(4, 1)->first();

slice(開始index, 取得する個数)

方法4

OK4
$collection[5] ?? null;
// 5番目の要素がない場合はnullを返す

NG1

NG1
$item = $collection[4];
// 要素が5つ未満の場合エラーが発生する
// => Undefined offset: 4

NG2

NG2
$collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
$item = $collection->shift(4)->last(); // 5

// $collection自体を書き換えてしまう
$collection->all(); // [6, 7, 8, 9, 10]

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1