Geoff Oliver

PHP function "is_json"

Posted on July 2, 2019 by Geoff Oliver

Sometimes, in PHP, you need to convert the contents of a variable that could be JSON string into an object (or array), but you might not know if that variable actually contains any JSON. At least that's something I run into a lot. So, I made this. Enjoy!

<?php

function is_json($string) {
    if (!is_string($string)) {
        return false;
    }

    if (mb_strlen($string) === 0) {
        return false;
    }

    $jsonBits = [['[', ']'], ['{', '}']];
    $start = mb_substr($string, 0, 1);
    $end = mb_substr($string, -1, 1);

    foreach ($jsonBits as $bits) {
        if ($start === $bits[0] && $end === $bits[1]) {
            return true;
        }
    }

    return false;
}

?>
© 2019 Geoff Oliver · Powered by another stupid blog thing