November 29, 2016 —John Koster
forget($key)
The forget
method removes an item from the collection based on given $key
. The forget
method returns a reference to the original collection, meaning it modifies the collection instance it was called on.
The following code example should how the forget
method can be used to remove an item from a collection:
1<?php 2 3use Illuminate\Support\Collection; 4 5// Create a new collection instance. 6$collection = new Collection([ 7 'first' => 'I am first', 8 'second' => 'I am second' 9]);10 11// Remove the 'first' item from the collection.12$collection->forget('first');
The $collection
will now contain only the second
item, and will have a structure similar to the following:
1object(Illuminate\Support\Collection)[133]2 protected 'items' =>3 array (size=1)4 'second' => string 'I am second' (length=11)
Numerical keys can also be passed to the forget
method to remove items from a collection:
1<?php 2 3use Illuminate\Support\Collection; 4 5// Create a new collection. 6$collection = new Collection([ 7 'I am first', 8 'I am second' 9]);10 11// Remove the 'first' item from the collection12// using a numerical key.13$collection->forget(0);
Like before, the $collection
will have a structure similar to the following output:
1object(Illuminate\Support\Collection)[133]2 protected 'items' =>3 array (size=1)4 1 => string 'I am second' (length=11)
∎
The following amazing people help support this site and my open source projects ♥️
If you're interesting in supporting my work and want to show up on this list, check out my GitHub Sponsors Profile.