Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

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?

like image 238
Vipul Sharma Avatar asked Jan 03 '13 10:01

Vipul Sharma


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 object is empty or not in PHP?

$x = (array)$obj; if (empty($x)) ... Or cast to an array and count() : if (count((array)$obj)) ...

How check object is null or not in PHP?

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.

What is stdClass object in PHP?

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.


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

like image 105
KingCrunch Avatar answered Oct 15 '22 04:10

KingCrunch


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

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

like image 31
moonwave99 Avatar answered Oct 15 '22 04:10

moonwave99