Possible Duplicate:
How to Check if an Object is empty in PHP
I have this empty object
Array ( [cart_items] => stdClass Object ( ) )
When I use empty()/is_null()
, it doesn't work. When I use sizeof($object)
, it returns one.
How can I check it?
2 Answers. Show activity on this post. $tmp = (array) $object; var_dump(empty($tmp));
$x = (array)$obj; if (empty($x)) ... Or cast to an array and count() : if (count((array)$obj)) ...
The is_null() function checks whether a variable is NULL or not. This function returns true (1) if the variable is NULL, otherwise it returns false/nothing.
The stdClass is the empty class in PHP which is used to cast other types to object. It is similar to Java or Python object. The stdClass is not the base class of the objects. If an object is converted to object, it is not modified.
Cast to an array first
$tmp = (array) $object; var_dump(empty($tmp));
The reason is, that an object is an object and there is no useful definition of "an empty object", because there are enough classes out there, that only contains methods, but no properties. Should they considered as "empty"?
Check if count( (array)$yourObject) ) == 0
.
But I'd better define my own class, and provide it with a meaningful isEmpty()
method.
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