How to check that an object is empty in 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 emptyif ( $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()); // TRUEvar_dump($two == new stdClass()); // TRUEvar_dump($one == $two); // TRUE$two->test = TRUE;var_dump($two == new stdClass()); // FALSEvar_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); // TRUEunset($one->test, $two->test);var_dump($one == $two); // TRUE