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
Use the empty function or the
null coalescing operator (??)
: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: