How to check that an object is empty in PHP?
PhpObjectPhp Problem Overview
How to find if an object is empty or not in PHP.
Following is the code in which $obj
is holding XML data. How can I check if it's empty or not?
My code:
$obj = simplexml_load_file($url);
Php Solutions
Solution 1 - Php
You can cast to an array and then check if it is empty or not
$arr = (array)$obj;
if (!$arr) {
// do stuff
}
Solution 2 - Php
Edit: I didn't realize they wanted to specifically check if a SimpleXMLElement object is empty. I left the old answer below
Updated Answer (SimpleXMLElement):
For SimpleXMLElement:
If by empty you mean has no properties:
$obj = simplexml_load_file($url);
if ( !$obj->count() )
{
// no properties
}
OR
$obj = simplexml_load_file($url);
if ( !(array)$obj )
{
// empty array
}
If SimpleXMLElement is one level deep, and by empty you actually mean that it only has properties PHP considers falsey (or no properties):
$obj = simplexml_load_file($url);
if ( !array_filter((array)$obj) )
{
// all properties falsey or no properties at all
}
If SimpleXMLElement is more than one level deep, you can start by converting it to a pure array:
$obj = simplexml_load_file($url);
// `json_decode(json_encode($obj), TRUE)` can be slow because
// you're converting to and from a JSON string.
// I don't know another simple way to do a deep conversion from object to array
$array = json_decode(json_encode($obj), TRUE);
if ( !array_filter($array) )
{
// empty or all properties falsey
}
Old Answer (simple object):
If you want to check if a simple object (type stdClass
) is completely empty (no keys/values), you can do the following:
// $obj is type stdClass and we want to check if it's empty
if ( $obj == new stdClass() )
{
echo "Object is empty"; // JSON: {}
}
else
{
echo "Object has properties";
}
Source: http://php.net/manual/en/language.oop5.object-comparison.php
Edit: added example
$one = new stdClass();
$two = (object)array();
var_dump($one == new stdClass()); // TRUE
var_dump($two == new stdClass()); // TRUE
var_dump($one == $two); // TRUE
$two->test = TRUE;
var_dump($two == new stdClass()); // FALSE
var_dump($one == $two); // FALSE
$two->test = FALSE;
var_dump($one == $two); // FALSE
$two->test = NULL;
var_dump($one == $two); // FALSE
$two->test = TRUE;
$one->test = TRUE;
var_dump($one == $two); // TRUE
unset($one->test, $two->test);
var_dump($one == $two); // TRUE
Solution 3 - Php
You can cast your object into an array, and test its count like so:
if(count((array)$obj)) {
// doStuff
}
Solution 4 - Php
Imagine if the object is not empty and in a way quite big, why would you waste the resources to cast it to array or serialize it...
This is a very easy solution I use in JavaScript. Unlike the mentioned solution that casts an object to array and check if it is empty, or to encode it into JSON, this simple function is very efficient concerning used resources to perform a simple task.
function emptyObj( $obj ) {
foreach ( $obj AS $prop ) {
return FALSE;
}
return TRUE;
}
The solution works in a very simple manner: It wont enter a foreach loop at all if the object is empty and it will return true
. If it's not empty it will enter the foreach
loop and return false
right away, not passing through the whole set.
Solution 5 - Php
Using empty()
won't work as usual when using it on an object, because the __isset()
overloading method will be called instead, if declared.
Therefore you can use count()
(if the object is Countable).
Or by using get_object_vars()
, e.g.
get_object_vars($obj) ? TRUE : FALSE;
Solution 6 - Php
Another possible solution which doesn't need casting to array
:
// test setup
class X { private $p = 1; } // private fields only => empty
$obj = new X;
// $obj->x = 1;
// test wrapped into a function
function object_empty( $obj ){
foreach( $obj as $x ) return false;
return true;
}
// inline test
$object_empty = true;
foreach( $obj as $object_empty ){ // value ignored ...
$object_empty = false; // ... because we set it false
break;
}
// test
var_dump( $object_empty, object_empty( $obj ) );
Solution 7 - Php
there's no unique safe way to check if an object is empty
php's count() first casts to array, but casting can produce an empty array, depends by how the object is implemented (extensions' objects are often affected by those issues)
in your case you have to use $obj->count();
http://it.php.net/manual/en/simplexmlelement.count.php
(that is not php's count http://www.php.net/count )
Solution 8 - Php
If you cast anything in PHP as a (bool), it will tell you right away if the item is an object, primitive type or null. Use the following code:
$obj = simplexml_load_file($url);
if (!(bool)$obj) {
print "This variable is null, 0 or empty";
} else {
print "Variable is an object or a primitive type!";
}
Solution 9 - Php
in PHP version 8
consider you want to access a property of an object, but you are not sure that the object itself is null or not and it could cause error. in this case you can use Nullsafe operator
that introduced in php 8
as follow:
> $country = $session?->user?->getAddress()?->country;
Solution 10 - Php
If an object is "empty" or not is a matter of definition, and because it depends on the nature of the object the class represents, it is for the class to define.
PHP itself regards every instance of a class as not empty.
class Test { }
$t = new Test();
var_dump(empty($t));
// results in bool(false)
There cannot be a generic definition for an "empty" object. You might argue in the above example the result of empty()
should be true
, because the object does not represent any content. But how is PHP to know? Some objects are never meant to represent content (think factories for instance), others always represent a meaningful value (think new DateTime()
).
In short, you will have to come up with your own criteria for a specific object, and test them accordingly, either from outside the object or from a self-written isEmpty()
method in the object.
Solution 11 - Php
I was using a json_decode of a string in post request. None of the above worked for me, in the end I used this:
$post_vals = json_decode($_POST['stuff']);
if(json_encode($post_vals->object) != '{}')
{
// its not empty
}
Solution 12 - Php
$array = array_filter($array);
if(!empty($array)) {
echo "not empty";
}
or
if(count($array) > 0) {
echo 'Error';
} else {
echo 'No Error';
}
Solution 13 - Php
Simply check if object type is null or not.
if( $obj !== null )
{
// DO YOUR WORK
}
Solution 14 - Php
Based on this answer from kenorb, here's another one-liner for objects with public vars:
if (!empty(get_object_vars($myObj))) { ... }
For objects with private or protected vars, better to cast to an array as others have mentioned.
Solution 15 - Php
count($the_object) > 0 this is working and can be use for array too