Reputation: 2679
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);
Upvotes: 126
Views: 243264
Reputation: 31
Based on this answer from kenorb, here's another one-liner for objects with public vars:
if (!empty(get_object_vars($myObj))) { ... }
Edit: Thanks to @mickmackusa's comment below - below is a more succinct one-liner, since this converts the object to an associative array (of accessible properties), and an empty array is falsy in PHP.
if (get_object_vars($myObj)) { ... }
Edit 2: In the event that your object is not a true object, get_object_vars()
may produce warnings or alerts. This checks that the var is an object before ensuring that it's populated:
if (is_object($myObj) && get_object_vars($myObj)) { ... }
Just to reiterate - this is for objects with public/accessible variables. Objects with static, private, or protected vars will render false, which may be unexpected. See https://www.php.net/manual/en/function.get-object-vars.php
Upvotes: 1
Reputation: 287
count($the_object) > 0 this is working and can be use for array too
Upvotes: 0
Reputation: 151
Simply check if object type is null or not.
if( $obj !== null )
{
// DO YOUR WORK
}
Upvotes: 0
Reputation: 4645
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;
Upvotes: 2
Reputation: 14391
You can cast to an array and then check if it is empty or not
$arr = (array)$obj;
if (!$arr) {
// do stuff
}
Upvotes: 156
Reputation: 1979
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.
Upvotes: 17
Reputation: 1780
You can cast your object into an array, and test its count like so:
if(count((array)$obj)) {
// doStuff
}
Upvotes: 30
Reputation: 3231
Edit: I didn't realize they wanted to specifically check if a SimpleXMLElement object is empty. I left the old answer below
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
}
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
Upvotes: 42
Reputation: 2491
$array = array_filter($array);
if(!empty($array)) {
echo "not empty";
}
or
if(count($array) > 0) {
echo 'Error';
} else {
echo 'No Error';
}
Upvotes: -1
Reputation: 1974
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!";
}
Upvotes: 1
Reputation: 166359
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;
Upvotes: 11
Reputation: 2718
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
}
Upvotes: 0
Reputation: 14596
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 ) );
Upvotes: 7
Reputation: 358
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.
Upvotes: 0
Reputation:
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 )
Upvotes: 2