Laravel 5: Retrieving Elements from an Array With get

April 11, 2018 —John Koster

The get helper method will retrieve an item from the given $array using dot notation. This allows developers to retrieve items from the array at arbitrary depths quickly, without having to use PHP's array syntax.

#Signature

The signature of the get method is:

1public static function get(
2 $array,
3 $key,
4 $default = null
5);

#Example Use

Assuming the following array:

1$anArray = [
2 'nested_array_one' => [
3 'nested_array_two' => [
4 'key' => 'value'
5 ]
6 ]
7];

We can quickly retrieve the value for key like so:

1use Illuminate\Support\Arr;
2 
3$value = Arr::get(
4 $anArray,
5 'nested_array_one.nested_array_two.key'
6);

Where the alternative syntax would be:

1$value = $anArray['nested_array_one']
2 ['nested_array_two']
3 ['key'];

While PHP's array access syntax may be a little shorter, using dot notation is easier to read. We can also specify a $default value, which will be returned if there is no matching $key found in the array.

1use Illuminate\Support\Arr;
2 
3$value = Arr::get(
4 $anArray,
5 'nested_array_one.nested_array_two.does_not_exist',
6 'default value'
7);

$value would then have the value of default value. Using this method is shorter than using PHP's array access syntax and the isset function, where we would have to check at each level if the key exists or not.

#Global array_get Helper Function

The array_get function is a shortcut to calling Arr::get. This function is declared in the global namespace.

Some absolutely amazing
people

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.