How to unset (remove) a collection element after fetching it? Ask Question

How to unset (remove) a collection element after fetching it? Ask Question

I have a collection which I want to iterate and modify while I fetch some of its elements. But I could't find a way or method to remove that fetched element.

$selected = []; 
foreach ($collection as $key => $value) {
      if ($collection->selected == true) {
          $selected[] = $value;
          unset($value);
      }
}

This is just a representation of my question for demonstration.

After @Ohgodwhy advice the forget() function I checked it again and saw that I actually misunderstood the function. It was exactly as I was looking for.

So for working solution I have added $collection->forget($key) inside the if statement.

以下は、@Ohgodwhy のソリューションを使用した、私の問題の実際の解決策です。

$selected = []; 
foreach ($collection as $key => $value) {
      if ($collection->selected == true) {
          $selected[] = $value;
          $collection->forget($key);
      }
}

(これは単なるデモンストレーションです)

ベストアンサー1

使いたいのは->forget()

$collection->forget($key);

リンク先メソッドのドキュメントを忘れる

おすすめ記事