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.
Or you can use reject
method
$newColection = $collection->reject(function($element) {
return $item->selected != true;
});
or pull
method
$selected = [];
foreach ($collection as $key => $item) {
if ($item->selected == true) {
$selected[] = $collection->pull($key);
}
}
Laravel Collection
implements the PHP ArrayAccess interface (which is why using foreach
is possible in the first place).
If you have the key already you can just use PHP unset
.
I prefer this, because it clearly modifies the collection in place, and is easy to remember.
foreach ($collection as $key => $value) {
unset($collection[$key]);
}
If you know the key which you unset then put directly by comma separated
unset($attr['placeholder'], $attr['autocomplete']);
I'm not fine with solutions that iterates over a collection and inside the loop manipulating the content of even that collection. This can result in unexpected behaviour.
See also here: https://stackoverflow.com/a/2304578/655224 and in a comment the given link http://php.net/manual/en/control-structures.foreach.php#88578
So, when using foreach
if seems to be OK but IMHO the much more readable and simple solution is to filter your collection to a new one.
/**
* Filter all `selected` items
*
* @link https://laravel.com/docs/7.x/collections#method-filter
*/
$selected = $collection->filter(function($value, $key) {
return $value->selected;
})->toArray();
You would want to use ->forget()
$collection->forget($key);
Link to the forget method documentation