November 29, 2016 —John Koster
get($key, $default = null)
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 given $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.
The following code sample demonstrates the use of the get
method:
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// I am second12$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<?php 2 3// null 4$value = $collection->get('third'); 5 6// default 7$value = $collection->get('third', 'default'); 8 9// default10$value = $collection->get('third', function() {11 return 'default';12});
The get
method can also retrieve items based on numeric keys:
1<?php 2 3use Illuminate\Support\Collection; 4 5// Create a new collection instance. 6$collection = new Collection([ 7 'first', 8 'second', 9 'third'10]);11 12// first13$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.