Home » Php » How to check if stdClass object is empty or not in php?

How to check if stdClass object is empty or not in php?

Posted by: admin April 23, 2020 Leave a comment

Questions:

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?

How to&Answers:

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”?

Answer:

Check if count( (array)$yourObject) ) == 0.

But I’d better define my own class, and provide it with a meaningful isEmpty() method.