How to check that an object is empty in PHP?

前端 未结 11 2059
不思量自难忘°
不思量自难忘° 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

    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.

提交回复
热议问题