Reputation: 4402
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.
Upvotes: 9
Views: 22147
Reputation: 390
You can also use array_get()
method, it's the same as Arr::get()
. Of course if you have laravel/helpers package installed.
Check the ./vendor/laravel/helpers/src/helpers.php
file.
Upvotes: 0
Reputation: 14941
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.
Upvotes: 14