April 22, 2018 —John Koster
The get
method can be used to retrieve an item from the collection based of its $key
. An optional $default
argument can be passed that will be returned if the supplied $key
does not exists in the collection. The $default
argument can be a simple value, or a callback that will be evaluated and the return value returned from the get
method.
1public function get(2 $key,3 $default = null4);
The following code sample demonstrates the use of the get
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]); 8 9// I am second10$second = $collection->get('second');
By default, the get
method will return null
if a $key
does not exist within the collection. However, a different value can be supplied, as well as a callback:
1// null 2$value = $collection->get('third'); 3 4// default 5$value = $collection->get('third', 'default'); 6 7// default 8$value = $collection->get('third', function() { 9 return 'default';10});
The get
method can also retrieve items based on numeric keys:
1use Illuminate\Support\Collection; 2 3// Create a new collection instance. 4$collection = new Collection([ 5 'first', 6 'second', 7 'third' 8]); 9 10// first11$value = $collection->get(0);
∎
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.