Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if JSON object is empty in PHP?

Tags:

I'm reading JSON data with PHP and that data contains empty objects (like {}). So the problem is, I have to handle the case when object is empty in different manner but I can't find good enough way to do the check. empty(get_object_vars(object)) looks too scary and very inefficient. Is there good way to do the check?

like image 682
vava Avatar asked Sep 07 '09 13:09

vava


People also ask

How check Stdclass object is empty in PHP?

2 Answers. Show activity on this post. $tmp = (array) $object; var_dump(empty($tmp));

How check JSON is valid or not in PHP?

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!

How do you check if the object is empty in PHP?

Therefore you can use count() (if the object is Countable). Or by using get_object_vars() , e.g.

How check if JSON array is empty PHP?

php $json = '{"hello": ["world"], "goodbye": []}'; $decoded = json_decode($json); print "Is hello empty? " . empty($decoded->{'hello'}); print "\n"; print "Is goodbye empty? " . empty($decoded->{'world'}); print "\n"; ?>


2 Answers

How many objects are you unserializing? Unless empty(get_object_vars($object)) or casting to array proves to be a major slowdown/bottleneck, I wouldn't worry about it – Greg's solution is just fine.

I'd suggest using the the $associative flag when decoding the JSON data, though:

json_decode($data, true) 

This decodes JSON objects as plain old PHP arrays instead of as stdClass objects. Then you can check for empty objects using empty() and create objects of a user-defined class instead of using stdClass, which is probably a good idea in the long run.

like image 178
Øystein Riiser Gundersen Avatar answered Sep 16 '22 14:09

Øystein Riiser Gundersen


You could cast it to an array (unfortunately you can't do this within a call to empty():

$x = (array)$obj; if (empty($x))     ... 

Or cast to an array and count():

if (count((array)$obj))     ... 
like image 31
Greg Avatar answered Sep 19 '22 14:09

Greg