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?
views:
786answers:
2
+3
A:
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))
...
Greg
2009-09-07 13:37:23
Isn't it the same as with get_object_vars? I.e. not really efficient? :)
vava
2009-09-07 13:46:05
I haven't tested it but unless you're having performance problems and have identified this as the bottleneck I don't think it's worth worrying yourself over it.
Greg
2009-09-07 14:43:18
It's not easy to stop worrying about unnecessary array transformations if you were a C++ programmer most of your life :) It means memory allocation and copying stuff for something that should take just a quick check if a bit is set.
vava
2009-09-07 14:57:35
+2
A:
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.
Øystein Riiser Gundersen
2009-09-07 14:07:11