Multi-dimensional isset

When working with large array/object data, especially when the overall structure is a mix of the two types, it is often useful to check if a given property exists.

This is something particularly relevant since data structures may change over time, needing to be reshaped.

For that task, I’ve written a small function that checks if a given sub-key exists in an array/object: if it does, the function will return its value, while if it doesn’t it will return either a specified default value, or boolean false.

The function produces the following results:

$arr = array(
	'a' => array(
		'b' => 42,
		'c' => new stdClass()
	)
);

$arr['a']['c']->foo = "bar";

var_dump( ev_isset( $arr, array( 'a', 'b' ) ) ); // returns "42"
var_dump( ev_isset( $arr, array( 'a', 'd' ) ) ); // returns false
var_dump( ev_isset( $arr, array( 'a', 'c', 'foo' ) ) ); // returns "bar"
var_dump( ev_isset( $arr, array( 'a', 'c', 'baz' ), 'default value' ) ); // returns "default value"

Enjoy!

Leave a Reply