8

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.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
O Connor
  • 4,236
  • 15
  • 50
  • 91
  • 1
    It depends upon the use case in context. – nice_dev Mar 15 '19 at 15:11
  • Above is my use case, get element from the array by array index key. Or it does not matter which one to use? – O Connor Mar 15 '19 at 15:14
  • 2
    The major difference is either your variable is an array or object. `data_get` will check if `$my_arr` is an object or not whereas `Arr::get` would assume it is an array. So if your data is an array, you can use `Arr::get` to save up some unnecessary checks. – Chin Leung Mar 15 '19 at 15:18
  • 2
    @OConnor if your usage is just limited to above ways of using it, `data_get()` is an overkill. `data_get()` also performs wildcard matches. – nice_dev Mar 15 '19 at 15:20
  • 1
    For both of you, that's the answer I am looking for. I did not think about that. Just now after reading your answer. thank! – O Connor Mar 15 '19 at 15:41

2 Answers2

12

It depends on the context to decide which one to use.

1. Wildcard matching

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"]

2. Variable Type

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.

Chin Leung
  • 14,621
  • 3
  • 34
  • 58
0

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.

Roman Samarsky
  • 320
  • 3
  • 10