Search the blog

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)
Tim Bennett is a Leeds-based web designer from Yorkshire. He has a First Class Honours degree in Computing from Leeds Metropolitan University and currently runs his own one-man web design company, Texelate.