- Instant help with your Php coding problems

Check if JSON key exists in PHP

Question:
How to check if JSON key exists in PHP?
Answer:
$houseNr = $user->address->houseNr ?? 'NA';
Description:

In the case of a JSON object if you try to access data with a key that doesn't exist then you will get the following warning:

Warning: Undefined property: stdClass::$myKey

To avoid this warning you need to test if the key exists or not. In PHP 7 the Null coalescing operator was introduced which makes this process quite simple:

$houseNr = $user->address->houseNr ?? 'NA';

 

Share "How to check if JSON key exists in PHP?"
Tags:
json, key, exists, php, access, check, isset
Technical term:
Check if JSON key exists in PHP
Interesting things
ChatGPT in a nutshell