Laravel 5

Laravel 5: Retrieving Elements from an Array With get


John Koster

Published on April 11, 2018

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.


The signature of the get method is:

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

Example Use

Assuming the following array:

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

We can quickly retrieve the value for key like so:

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

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;
3$value = Arr::get(
4 $anArray,
5 'nested_array_one.nested_array_two.does_not_exist',
6 'default value'

$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.