I have following JSON:
$p={
"main1" : [
{
"child1" : valueA,
"child2" : valueB,
"child3" : valueC,
},
{
"child1" : value1,
"child3" : value3,
},
],
"main2" : "valueMain2"
}
The element child2
has to be checked if it exists or not and then the value is taken. I am using json_decode:
$response = json_decode($p,true);
How do I check if an element exists or not in PHP? Do I have to make separate function or is there built-in functionality?
Simple function to validate JSON. If you have to validate your JSON in multiple places, you can always use the following function. function is_valid_json( $raw_json ){ return ( json_decode( $raw_json , true ) == NULL ) ? false : true ; // Yes!
$x = (array)$obj; if (empty($x)) ... Or cast to an array and count() : if (count((array)$obj)) ...
The simplest way to check if JSON is valid is to load the JSON into a JObject or JArray and then use the IsValid(JToken, JSchema) method with the JSON Schema. To get validation error messages use the IsValid(JToken, JSchema, IList<String> ) or Validate(JToken, JSchema, SchemaValidationEventHandler) overloads.
PHP has some built-in functions to handle JSON. First, we will look at the following two functions: json_encode() json_decode()
The same way you'd check if a key of any array exists:
with isset($array['key'])
or array_key_exists('key',$array)
.
Here's how I've been doing it.
$child2exists = count($response['main1']['child2']);
If ($child2exists == 1)
{
echo "EXISTS";
}
else
{
echo "DOESNT EXIST";
}
Hope this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With