PHP: how to check if an object's properties have values?

laukok picture laukok · Oct 12, 2013 · Viewed 8.4k times · Source

I use this to check if an object has properties,

function objectHasProperty($input){
        return (is_object($input) && (count(get_object_vars($input)) > 0)) ? true : false;
 }

But then I want to check further to make sure all properties have values, for instance,

stdClass Object
        (
            [package] => 
            [structure] => 
            [app] => 
            [style] => 
            [js] => 
        )

Then I want to return false if all the properties have empty values. Is it possible? Any hint and ideas?

Answer

George Brighton picture George Brighton · Oct 12, 2013

There are several ways of doing this, all the way up to using PHP's reflection API, but to simply check if all public properties of an object are empty, you could do this:

$properties = array_filter(get_object_vars($object));
return !empty($properties);

(The temporary variable $properties is required because you're using PHP 5.4.)