Skip to content
Advertisement

Detecting an object containing all empty string property values in php or laravel

I need to detect if an object’s (like the below one) all the properties has an empty string as value. How can I achieve this?

object(stdClass)#1282 (9) {
["first_name"]=>
string(0) ""
["last_name"]=>
string(0) ""
["company"]=>
string(0) ""
["address_1"]=>
string(0) ""
["address_2"]=>
string(0) ""
["city"]=>
string(0) ""
["state"]=>
string(0) ""
["postcode"]=>
string(0) ""
["country"]=>
string(0) ""
}

Advertisement

Answer

Since it is all empty strings/null these fields can be filtered out easily:

(bool) array_filter((array) $object)

If it has a single property that isn’t a “falsey” value you will get true.

FYI: This will also filter out other false values though like, 0,'0', false, etc …

PHP.net Manual – Function Reference array_filter

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement