Tariq Imtinan
Tariq Imtinan

Reputation: 104

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) ""
}

Upvotes: 0

Views: 462

Answers (2)

lagbox
lagbox

Reputation: 50491

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

Upvotes: 4

Andy Song
Andy Song

Reputation: 4684

This should only return true if all the properties are empty strings.

return collect((array)$obj)->every(function ($value, $key) {
    return trim($value) === '';
    
});

And if you are using PHP 7.4 and above this can be even shorter.

return collect((array) $obj)->every(fn ($v) => '' === trim($v));

Upvotes: 4

Related Questions