Heterogeneous Multi-dimensional Data Access in PHP

When was the last time you had to fetch some deeply nested data in PHP and ended up writing code that looked something like this?

$grandchild = isset( $data['parent'], $data['parent']['child'], $data['parent']['child']['grandchild'] ) ? $data['parent']['child']['grandchild'] : null;

Ugh.

Laravel has a function called array_get() which would allow you to fetch the data like this:

$grandchild = array_get( $data, 'parent.child.grandchild' );

This is great, but I decided to use Laravel’s approach for inspiration and improve on it. I wrote a similar function, but I decided to extend it to not only fetch deeply nested data from an array, but also from an object.

The result is a robust utility function that allows you to easily fetch deeply nested data from a heterogeneous multi-dimensional collection using dot notation:

If we re-write our initial code conundrum using this function, it looks almost identical to Laravel’s array_get():

$grandchild = get_value( $data, 'parent.child.grandchild' );

However, the real benefit comes when we need to access a data structure that may be a mixture of arrays and objects:

$data['parent']->child['grandchild'];

In this case, we would fetch the data using the exact same syntax with get_value()and would never encounter an Undefined index or Trying to get property of non-object notice if a key or property didn’t exist.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.