get($array, $key, $default = null)
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.
Assuming the following array:
1<?php
2
3$anArray = [
4 'nested_array_one' => [
5 'nested_array_two' => [
6 'key' => 'value'
7 ]
8 ]
9];
We can quickly retrieve the value for key
like so:
1<?php
2
3use Illuminate\Support\Arr;
4
5$value = Arr::get($anArray, 'nested_array_one.nested_array_two.key');
Where the alternative syntax would be:
1<?php
2
3$value = $anArray['nested_array_one']['nested_array_two']['key'];
While PHP's array access syntax may be a little shorter, using the 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.
1<?php
2
3use Illuminate\Support\Arr;
4
5$value = Arr::get(
6 $anArray,
7 'nested_array_one.nested_array_two.does_not_exist',
8 'default value'
9);
$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.
#array_get($array, $key, $default = null)
The array_get
function is a shortcut to calling Arr::get
. This function is declared in the global namespace.
∎