Previously I had gone through the function to create a slug from the given string.

Today, I came up with a problem. Using Jquery I used the same function to send two types of value: one being a string and another JSON encoded. Now I had to check them and use methods accordingly.

For this, I searched for the solution and came to a StackOverflow solution. However, for better understanding, I found another blog that suggested several methods.
Click here for the blog.

The solution I used is, I passed the data through the function

function isJSON($string){
return is_string($string) && is_array(json_decode($string, true)) && (json_last_error() == JSON_ERROR_NONE) ? true : false;
}

and used if-else to use the method accordingly

if($this->isJSON($string)) {
        $string = json_decode($hotspot);
       //something to be done
}
else {
    //something to be done
}

Another solution that I was suggested from Reddit is to make a function that checks the data by decoding it, if it is successfully decoded, it returns the decoded data otherwise it returns the original data itself.

function json_try_decode($json) {
    if (! is_string($json)) {
        return $json;
    }

    $result = json_decode($json);

    return $result === false
        ? $json
        : $result;
}

I hope this helps you with your problems too.