How to check that an object is empty in PHP?

前端 未结 11 2063
不思量自难忘°
不思量自难忘° 2020-11-29 03:31

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?

11条回答
  •  情歌与酒
    2020-11-29 04:13

    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
    

提交回复
热议问题