Loading..

Determine if a PHP variable is a JSON object or JSON array 0 0

Last updated on Dec 19, 2019 01:19 in HOW-TOS
Posted By reza saghafi

When decoding JSON in PHP the result, if successful, is always an array. This handy function lets you determine if a string variable is a JSON array or JSON object. If it’s invalid it will return false.

function getJSONType($json) {
    
    $obj = json_decode($json);
    
    // Not valid JSON
    if ($obj === null) {
        
        return false;    
        
    }

    $json = ltrim($json);

    // Object
    if (strpos($json, '{') === 0) {

        return 'object';

    }

    // Array
    if (strpos($json, '[') === 0) {

        return 'array';

    }

    return false;

}

var_dump(getJSONType('["foo", "bar"]')); // string(5) "array"
var_dump(getJSONType('{"foo": "bar"}')); // string(6) "object"
var_dump(getJSONType('dlkvjdlkfj')); // bool(false)

** The time is base on America/New_York timezone