LoginSignup
3
0

【Laravel】partitionメソッドで配列を分割しよう

Last updated at Posted at 2023-12-27

概要

知らなかったメソッドがあったので紹介
以下のように、条件を満たしている物が格納されている配列と、条件を満たしていない物が格納されている2つの配列が生成されっます

$collection = collect([1, 2, 3, 4, 5, 6]);

[$underThree, $equalOrAboveThree] = $collection->partition(function ($i) {
    return $i < 3;
});

$underThree->all();

// [1, 2]

$equalOrAboveThree->all();

// [3, 4, 5, 6

まとめ

自分は今までwhereなど使って冗長に書いてたので使っていこうと思います

3
0
1

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
3
0