Dealing with deeply-nested arrays

If you have a complex array, you can use data_get() helper function to retrieve a value from a nested array using "dot" notation and wildcard.

$data = [
0 => ['user_id' => 1, 'created_at' => 'timestamp', 'product' => {object Product}],
1 => ['user_id' => 2, 'created_at' => 'timestamp', 'product' => {object Product}],
2 => etc
];
 
// Now we want to get all products ids. We can do like this:
 
data_get($data, '*.product.id');
 
// Now we have all products ids [1, 2, 3, 4, 5, etc...]

In the example below, if either request, user or name are missing then you'll get errors.

$value = $payload['request']['user']['name'];
 
// The data_get function accepts a default value, which will be returned if the specified key is not found.
 
$value = data_get($payload, 'request.user.name', 'John')

Tip given by @mattkingshott

Like our articles?

Become a Premium Member for $129/year or $29/month
What else you will get:
  • 68 courses (1188 lessons, total 43 h 18 min)
  • 90 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord

Recent New Courses