40

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?

Community
  • 1
  • 1
Vipul Sharma
  • 431
  • 1
  • 4
  • 12
  • check this `empty($object['cart_items'])` – rynhe Jan 03 '13 at 10:38
  • I'm getting this error Fatal error: Cannot use object of type Zend_Session_Namespace as array and when i use it like this empty($object->cart_items), then also it doesn'w work. – Vipul Sharma Jan 03 '13 at 10:41

2 Answers2

71

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

KingCrunch
  • 128,817
  • 21
  • 151
  • 173
20

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

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

moonwave99
  • 21,957
  • 3
  • 43
  • 64