Posted by & filed under PHP.

 * This class will safely parse complex objects or arrays with possible missing keys
 * Usage: obj::query($obj, 'dot.separated.syntax');
class obj {
     * Parse the provided object
     * @param $object mixed The complex object you're going to parse
     * @param $path string The dot separated path you would like to query the object with
    public static function query($object, $path) {
        $paths = explode('.', $path);
        return self::recurse($object, $paths);

     * The function that does the real work
     * @param $object mixed
     * @param $paths array
    protected static function recurse($object, $paths) {
        if (!$object) {
            return null;
        if (!is_array($object) && !is_object($object)) {
            return $object;

        $newPath = array_shift($paths);

        if (is_array($object) && isset($object[$newPath])) {
            return self::recurse($object[$newPath], $paths);
        } else if (is_object($object) && isset($object->$newPath)) {
            return self::recurse($object->$newPath, $paths);
        } else {
            return null;

$data = '{
  "x": {
    "y": true,
    "z": null,
    "w": false,
    "l": "banana",
    "a": {
      "b": {
        "c": "d",
        "d": "e"

$complexArray = json_decode($data, true);
$complexObject = json_decode($data);
$complexMixed = array(
        'x' => json_decode('{"name": "so complex"}')

echo "Should be banana: ";
var_dump(obj::query($complexArray, 'x.l'));

echo "Should be 'e': ";
var_dump(obj::query($complexArray, 'x.a.b.d'));

echo "Should be NULL: ";
var_dump(obj::query($complexArray, 'a.b.c.d.e.f.g'));

echo "Should be TRUE: ";
var_dump(obj::query($complexObject, 'x.y'));

echo "Should be 'so complex': ";
var_dump(obj::query($complexMixed, ''));

Thomas Hunter II

Thomas is passionate about technology and building products. A web design business created while attending college slowly evolved into a brick and mortar on Main St. of his small Midwestern hometown. His desire for fame and fortune led to the co-founding of a Y Combinator startup and a life in California.
Hey there! I'm currently writing a book on Microservices which I expect to release in early 2017. If you're interested in getting updates please signup here. More info about the Book