1
1

More than 1 year has passed since last update.

Laravel:emptyの罠

Last updated at Posted at 2022-03-04

emptyの使い方、完全に勘違いしていた。

Laravelのcollectionに対して空かどうかの判定はisEmpty()を使う。
普通にforeachでイテレートできるのでempty(collect([]))で判定できるもんだと思っていたら、全部trueになってた。

Laravel 5.8 コレクション

Illuminate\Support\Collectionクラスは配列データを操作するための、書きやすく使いやすいラッパーです。

例えばこのような例や

$collection = collect([]);
while(!empty($collection)) {
    // do
}
// => 無限ループする

ガード節などでうまくいかない。

if (!$collection) {
    return; // => ここに入ることはない。
}
// do

友人の言葉を借りると、

empty($var) !isset($var) || $var == falseのこと
$var = collect([])であるとすると
値であるcollect([]) を代入しているから
!isset($var) // === false 
($var == false) // === false
より常にtrueになる

ちなみにisEmptyは内部でemptyを呼び出している。

collection.php
public function __construct($items = [])
{
    $this->items = $this->getArrayableItems($items);
}

protected function getArrayableItems($items)
{
    if (is_array($items)) {
        return $items;
    } elseif ($items instanceof self) {
        // collection => array
        return $items->all();
    }  //...
}

public function isEmpty()
{
    return empty($this->items);
}

まとめ

collection(というか自作クラス)にはemptyは使えない。
emptyやissetだけだと意図が伝わりにくいので、is_nullや比較演算子などで書いた方が良い気がした。
あとはLarastan入れれば教えてくれる見たい。
emptyの諸々の判定はマニュアルを見てください。

そういえば、phpってなんでコレクションないんだろう。

1
1
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
1
1