
Why empty() doesn’t work with empty objects in PHP
When working with PHP, it’s common to want to check whether a variable is “empty.” If you’re dealing with objects, you’ve probably encountered this unexpected behavior:
<?php $obj = new stdClass(); print_r($obj);
This outputs:
stdClass Object ( )
It clearly looks empty! But if you use empty()
to check:
<?php var_dump(empty($obj)); // false
It returns false. How can something that appears empty not be considered empty? Let’s break down why this happens and how to solve it correctly.
What does PHP consider “Empty”?
The empty()
function in PHP checks whether a variable is undefined or holds a “falsy” value, such as:
""
(empty string)0
(integer zero)"0"
(string zero)null
false
[]
(empty array)- unset variables
But here’s the catch: objects are not included in this list. Even if an object has no properties, it’s still a valid instance of a class and PHP considers it as “non-empty.”
The problem with empty($obj)
<?php $obj = new stdClass(); if (empty($obj)) { echo "The object is empty."; } else { echo "The object is NOT empty."; }
This will output:
The object is NOT empty.
Why? Because $obj
is a valid instance of stdClass
. PHP sees it as a value that exists, regardless of whether it contains any properties.
How to check if an object is actually empty
Most of the time, what we really want to know is whether the object has any defined properties. To do that, we can cast the object to an array and then use empty()
on the result:
<?php $obj = new stdClass(); if (empty((array) $obj)) { echo "The object has no properties."; } else { echo "The object has properties."; }
This will correctly output:
The object has no properties.
You can also create a reusable helper function:
<?php function isObjectEmpty($obj): bool { return empty((array) $obj); }
Usage example:
<?php $obj = new stdClass(); var_dump(isObjectEmpty($obj)); // true $obj->name = "Test"; var_dump(isObjectEmpty($obj)); // false
Common use cases
This kind of check is useful when:
- You’re working with JSON data decoded into objects.
- You’re integrating with APIs and need to validate if the response contains data.
- You use objects as temporary containers for dynamic properties.
In PHP, objects are never considered empty by the empty()
function, even if they have no properties at all. If you need to check whether an object is truly empty, the reliable way is to cast it to an array:
empty((array) $obj)
This simple trick helps you accurately evaluate empty data structures and avoid logic errors in your code.