April 22, 2018 —John Koster
The pull
method will remove an item from the collection whilst returning its value. If the item is not in the collection, the optional $default
value will be returned. The pull
method will modify the original collection.
1public function pull(2 $key,3 $default = null4);
The following example demonstrates the basic use of the pull
method:
1use Illuminate\Support\Collection; 2 3// Create a new collection instance. 4$collection = new Collection([ 5 'first' => 'I am first', 6 'second' => 'I am second', 7 'third' => 'I am third' 8]); 9 10// Pull the third value from the collection.11$value = $collection->pull('third');12 13// null14$doesNotExist = $collection->pull('non-existent');15 16// default-value17$alsoDoesNotExist = $collection->pull(18 'non-existent',19 'default-value'20 );
After the above code has executed, the $value
variable would contain the value I am third
and the $collection
variable would contain a value similar to the following output:
1object(Illuminate\Support\Collection)2 protected 'items' =>3 array4 'first' => string 'I am first'5 'second' => string 'I am second'
∎
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.