Categories
Uncategorized

get_deep_value in PHP

Ever have an array in PHP that looks like this?

$data = [ 'one' => [ 'two' => [ 'four' => 'bar', 'three' => 'foo' ] ] ];

It can be annoying to pull deep values from such an array because if you access an array key that doesn’t exist, PHP will throw an exception.

do_something_with( $data['one']['two']['six'] ); // throws an exception!

You could check each level of the data using array_key_exists() like this:

if ( array_key_exists( 'one', $data )  && array_key_exists( 'two', $data['one'] ) && array_key_exists( 'three', $data['one']['two'] ) ) {
  do_something_with( $data['one']['two']['three'] );
}

But that would take forever. PHP’s isset() method fortunately makes this somewhat more clean:

if ( isset( $data['one']['two']['three'] ) ) {
  do_something_with( $data['one']['two']['three'] ); 
}

But that’s still a lot to type, especially if you have to do it several times. In JavaScript-land we have some nice patterns around this sort of thing. Underscores and Lodash have the _.get() method, so I’ve re-created that in PHP here as get_deep_value().

The first argument is the array you want to search, and the second argument is an array of keys, one per level.

Now you can just write:

if ( $value = Get_Deep_Value::get_deep_value( $data, ['one', 'two', 'three'] ) {
  do_something_with( $value ); 
}

Or maybe even, if your function is ok with null values, just simply:

do_something_with( Get_Deep_Value::get_deep_value( $data, ['one', 'two', 'three'] ) );

I’m just posting the gist here for now because I’m not quite sure how to release this as a general module in the PHP ecosystem yet. If you have any helpful suggestions, please add them in the comments!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s