skip to Main Content

I am working on to decode json data and get value from array. It is working fine if there is value in json array. But in some cases json is coming empty and i need to validate it. If json is empty then it will go in else condition.

 $response = '[{"NUMBER":"","INV-NO":"","PL-NUM":"","TYPE":""},{"NUMBER":"","INV-NO":"","PL-NUM":"","TYPE":""}]';
 $jsondata = json_decode($response,true); 

 if(!empty($jsondata))
 {
echo "value in json data";
 }else{

echo "no value";
 }

2

Answers


  1. Do something like this

      empty(!json_decode($response,true)) ? print "value in json data" : print "no value";
    
    Login or Signup to reply.
  2. You need to traverse each sub-child of array and get the count of not-empty values. Then you can apply check based on that

    function getNotEmptyValuesCountOfArray($n)
    {
        return count(array_filter($n));
    }
    $response = '[{"NUMBER":"","INV-NO":"","PL-NUM":"","TYPE":""},{"NUMBER":"","INV-NO":"","PL-NUM":"","TYPE":""}]';
    $jsondata = json_decode($response,true); 
    $count = array_sum(array_map('getNotEmptyValuesCountOfArray',$jsondata));
    if($count  > 0)
    {
      echo "value in json data";
    }else{
      echo "no value";
    }
    

    Output: https://3v4l.org/WMtas

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search