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:


 

This outputs:

stdClass Object ( )

 

It clearly looks empty! But if you use empty()to check:


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)


 

This will output:

The object is NOT empty.

Why? Because $objis 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:


 

This will correctly output:

The object has no properties.

 

You can also create a reusable helper function:


 

Usage example:

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.

 

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Back to Top
0
Would love your thoughts, please comment.x
()
x