How to know if a stdClass is empty?

Asked

Viewed 1,640 times

3

In PHP, to check if a array is empty we can use the function (or language constructor) empty.

Thus:

$a = array();

$b = array(1, 2);

var_dump(empty($a), empty($b)); // Imprime: bool(true), bool(false)

But the same does not happen with stdClass.

$a = (object) array();

$b = (object)array('nome' => 'wallace');

$c = new stdClass(); // A mesma coisa que $a

var_dump(empty($a), empty($b), empty($c)); // Imprime: bool(false), bool(false), bool(false)

See on IDEONE

So what’s the way to know that an object stdClass is empty or not in PHP?

2 answers

4


You could use the function get_object_vars, to return the properties of stdClass in a array. Then you could use the function count or empty, to know if it is empty or not.

Example:

$object = new stdClass;

count(get_object_vars($object)) == 0;// Imprime: bool(true)

$array = get_object_vars($object);

var_dump(empty($array)); // Imprime: bool(true);
  • James, I think you’re new to stackoverlow. You should use the comments for this sort of thing. This is usually a flashy for negative votes, but to help you, I will edit your answers, to you how it could improve, okay?

  • This should be posted in the comments. When you will present a hypothesis, you use the comments. When you will present a concrete solution, you use the answer.

  • Don’t be in a hurry to answer, just hurry up and help.

  • I guess we can remove that comment jug from here

  • @Wallacemaxters just so I know, you would remove all comments in this case? I was wondering if I was asking for approval to do it, or if each one has to delete his comment to clear, thanks!

  • It is that the subject has escaped the context of the question. This is not recommended

Show 1 more comment

1

Just for extra help, if anyone needs it, we could do it using a loop on top of the stdClass. If you enter the foreach is because it is an object with properties. If not, it is empty.

Behold:

function is_empty_object(stdClass $object)
{

    foreach($object as $value) return false;

    return true;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.