Iter Ator
Iter Ator

Reputation: 9289

How is it possible to check if any of the properties of an object is empty?

I would like to check, if any of the properties of an object is empty, without manually checking each one. This is how I do it now:

class MyClass {
    public $a;
    public $b;
    public $c;
}

Then:

$item = new MyClass();

// ...
$item->a = 10;
$item->b = 20;
// ...

// TODO:
$hasEmpty = empty($item->a) || empty($item->b) || empty($item->c);

How is it possible without manually checking each property?

Upvotes: 0

Views: 1161

Answers (4)

Luca Murante
Luca Murante

Reputation: 317

The best way is to use PHP Reflection. This sample code checks ALL properties:

<?php

$item = new MyClass();

$reflect = new ReflectionClass($item);

$props = $reflect->getProperties(ReflectionProperty::IS_PUBLIC | ReflectionProperty::IS_PROTECTED);

$is_empty = false;

foreach ($props as $prop) {
    if (empty($prop->getValue())) {
        $is_empty = true;
        // We break, since it's useless to continue over
        break;
    }
}

// Test it
var_dump($is_empty);

?>

Upvotes: 0

paulin-crtn
paulin-crtn

Reputation: 383

I think you have to loop through the object.

function isObjectEmpty($obj) {
  foreach ($obj as $value) {
    if (!isset($value)) {
      return true;
    }
  }
  return false;
}

Upvotes: 0

nice_dev
nice_dev

Reputation: 17805

You can actually typecast object to an array and then use array_filter on it to filter out the empty values and check it's size like below:

<?php

$hasEmpty = count(array_filter((array)$item,fn($v) => empty($v))) > 0;

var_dump($hasEmpty);

Online Demo

Another way could be by implementing ArrayAccess interface and accessing object keys just like array keys and performing the empty checks, but I will leave it upto the reader to implement them as an exercise if they wish to.

Upvotes: 2

X3R0
X3R0

Reputation: 6324

I suggest destructuring your object and then loop through and see if any are null.

// create class
class MyClass {
    public $a;
    public $b;
    public $c;
}

// create object
$item = new MyClass();
$item->a = 10;
$item->b = 20;

// get vars and test if any properties are null
$vars = get_object_vars($item);
$isNull = false;
foreach($vars as $var){
    if(empty($var)){
       $isNull = true;
    }
}

or you could turn this into a function

function areAnyPropertiesEmpty($class){
     $vars = get_object_vars($class);
    $isNull = false;
    foreach($vars as $var){
       if(empty($var)){
           $isNull = true;
       }
    }
    return $isNull;
}

Upvotes: 1

Related Questions