November 30, 2016 —John Koster
pull($key, $default = null)
The pull
method will remove an item from the collection while 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.
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 'third' => 'I am third'10]);11 12// Pull the third value from the collection.13$value = $collection->pull('third');14 15// null16$doesNotExist = $collection->pull('non-existent');17 18// default-value19$alsoDoesNotExist = $collection->pull('non-existent', 'default-value');
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)[133]2 protected 'items' =>3 array (size=2)4 'first' => string 'I am first' (length=10)5 'second' => 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.