DEV Community

Discussion on: Are there functions similar to Ruby's `dig` in other languages?

Collapse
 
patrickcarlohickman profile image
Patrick Carlo-Hickman

PHP7 introduced the null coalesce operator (??) which will suppress errors for the missing intermediate keys. So, this will work without errors/warnings:

$phone = $orders[0]['customer']['phone'] ?? null;

The Laravel framework in PHP also has array helpers which allow you to access values using "dot" notation:

$phone = array_get($orders, '0.customer.phone');

You can pass a third value to use as the default if it doesn't exist, but the default is null without it.

This helper function is a shortcut to access the Arr::get() method mentioned by Suhayb Alghutaymil.