0

How do I make sure that a key exists in a complex PHP variable? Following is the JSON output of a Google API:

{
   "destination_addresses" : [
      "India"
   ],
   "origin_addresses" : [
      "India"
   ],
   "rows" : [
      {
         "elements" : [
            {
               "distance" : {
                  "text" : "86 m",
                  "value" : 86
               },
               "duration" : {
                  "text" : "1 min",
                  "value" : 24
               },
               "status" : "OK"
            }
         ]
      }
   ],
   "status" : "OK"
}

sometimes it changes to this:

{
   "destination_addresses" : [ "20.348326,85.8160893" ],
   "origin_addresses" : [ "20.3487083,-85.8157674" ],
   "rows" : [
      {
         "elements" : [
            {
               "status" : "ZERO_RESULTS"
            }
         ]
      }
   ],
   "status" : "OK"
}

I have converted this JSON into a PHP variable using

$response_a = json_decode($response, true);

Now, how do I make sure that I read the key distance only when it is there in the output e.g:

$dist = $response_a['rows'][0]['elements'][0]['distance']['text'];

in case of response 1; otherwise

$response_a['rows'][0]['elements'][0]['status'] 
fmw42
  • 46,825
  • 10
  • 62
  • 80

1 Answers1

1

You could use isset(...) eg:

if (isset($response_a['rows'][0]['elements'][0]['distance']['text'])) {
      $dist = $response_a['rows'][0]['elements'][0]['distance']['text']; 
} else {
      $dist =1;

}  ;
ScaisEdge
  • 131,976
  • 10
  • 91
  • 107