With data_get()
helper function, we can get value of a nested array using dot .
notation as following:
$my_arr = [
'a' => ['lower' => 'aa', 'upper' => 'AAA',],
'b' => ['lower' => 'bbb', 'upper' => 'BBBBB',],
];
Thus, I can get lower a
by doing this.
data_get($my_arr, 'a.lower');
And you also do the following.
Arr::get('a.lower');
In case I just want to get only the first level of the array. I just can do both:
data_get($my_arr, 'a');
OR
Arr::get($my_arr, 'a');
Which one do you recommend me and why? I just want to keep improving my Laravel experience and get good advice from senior developers to choose the best options at the moment.
It depends on the context to decide which one to use.
If you need to use wildcard in your index, you have to go with data_get
as Arr::get
does not support wildcards.
Example:
Arr::get($my_arr, '*.lower'); // null
data_get($my_arr, '*.lower'); // ["aa", "bbb"]
Arr::get
simply assumes that your variable is an array. Therefore, if you use an object, you have to go with data_get
. If, however you are sure your variable is an array and you don't need wildcards, you should proceed with Arr::get
to avoid unnecessary checks from data_get
that evaluates to see if your variable is an object or array.