How to check if a JSON Object is available or not in PHP

By Faruque Ahamed Mollick

In many times you may need to check if a JSON object property is available or not and depending on this you need to return some value, otherwise, you may get an error if the object property is not available inside JSON formatted data.

For this tutorial we have taken the below JSON formatted data:

<?php
$json_data={
  "main" : [
    {
      "temperature" : valueA,
      "pressure" : valueB,
      "humidity" : valueC,
    },
  ],
  "description" : "drizzle"
}
?>

Now we will check if the “description” object property is available or not in PHP. So below is the PHP code which will do this task:



$get_json = json_decode($json_data);
if (isset($get_json->description)) {
   echo $get_json->description; // valueMain2
}
else {
echo "description is not available";
}

The above code simply decodes the JSON formatted data using json_decode PHP function and then check if description object is available in the JSON. If it is available then it will be displayed on the web page and if not then it will echo the text “description is not available”.

I suggest you try this on your server by creating JSON formatted data. First, try with keeping the description property in the JSON formatted text and then run it again after removing the description property.

So was that not so easy? Did you like that? If you have any question related to this tutorial then you can ask me. I am always ready to help you and try my best.

Leave a Reply

Your email address will not be published. Required fields are marked *