skip to Main Content

I often deal with large JSON objects. In many cases data is nested within deep layers, and isn’t guaranteed to be present.

For example, I would love to use the following code:

$images = $json['data']['article']['media']['assets']['crops']['featured-image'];

However, perhaps the article doesn’t have any media, and even if it does, its not a featured-image but a different kind. Then I have a nice error that I need to deal with.

I’d like to avoid nested if statements or a check that looks like:

if (isset($json['data']) && isset($json['data']) && isset($json['data'])) {
  // do something
}

I would like to be able to check something directly, and if it exists then I get the value, and if it doesn’t, I get empty or false or null, or whatever suits.

There must be a simpler, cleaner, way that I’ve missed all this time?

2

Answers


  1. Use the empty function or the null coalescing operator (??):

    //With empty
    empty($array['fake']['fake']['fake']); // true (value doesn't exists, so is empty)
    
    //With the null coalescing operator (??)
    $array['fake']['fake']['fake'] ?? false // false (value doesn't exists, so it jumps to the false declaration);
    
    Login or Signup to reply.
  2. isset(), empty() and ?? operator are good options, however the array may contain a null or false or some value that evaluates to empty in the key you are testing.

    A more reliable option is to use array_key_exists() in conjunction with ?? operator which leads back to an empty array:

    array_key_exists ('may_exist_or_not3', $arr['may_exist_or_not1']['may_exist_or_not2'] ?? []);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search