1

I'm facing this dilemma, basically I want to create an error object if a certain task isn't met. Now to understand what I've got to send back to the user, I need to check to see if that error object is either empty or has data. The issue is this:

$obj = new stdClass();
var_dump(empty($obj)); // returns false

As you can see in this example, it's returning false instead of true as it's empty.

$o = new stdClass();
$a = array();

var_dump(empty($o));
var_dump(empty($a));

Example

This works perfectly fine for an array, but does anyone know why this is happening for objects?


I've read answers like this which state to cast it as an array, but my question is this:

Why does it return false when it's empty? What is the logic behind it? If I wanted an array, I would've started with that.

Community
  • 1
  • 1
Darren
  • 13,050
  • 4
  • 41
  • 79
  • 5
    [RTM](http://php.net/manual/en/function.empty.php#refsect1-function.empty-returnvalues) Also see: http://php.net/manual/en/types.comparisons.php – Rizier123 May 20 '15 at 10:37
  • 1
    If you really need to check if an object is empty, just cast it to an array: `if (empty((array)$stdClass))` – h2ooooooo May 20 '15 at 10:41
  • You are creating an object and assigning it to $obj that means $obj is not empty. – Mangesh Sathe May 20 '15 at 10:41
  • @Rizier123 Perfect, that's what I was looking for! if you chuck it up as an answer I'll accept – Darren May 20 '15 at 10:42
  • Then Empty function will check it is empty OR not. If its empty return TRUE else FALSE – Mangesh Sathe May 20 '15 at 10:44
  • 2
    If I were you and if I coded what you did, I'd have my object implement method `isEmpty()` which would check properties that contain errors. Then I can just use OO approach, if I'm using objects already, and I can do `if($myObject->isEmpty())` or even better `if($myObject->hasErrors())`. I don't see why would anyone use procedural approach at all. Avoiding setting mines removes all possibility of setting one off. – N.B. May 20 '15 at 10:46
  • 1
    @Darren - we often miss the forest because of the damn trees, but coffee should help with that. Anyway, glad I could help a bit :> – N.B. May 20 '15 at 10:51
  • @N.B. That would be my accepted answer if you want to post it! You get 1000 cookies for pointing out my idiocy! :P – Darren May 20 '15 at 10:52
  • 1
    It's all good, the question was about `empty` construct and objects so the provided answer is answering that, for any future googlers that stumble upon here so it's all good if you ask me. I'm ok with helping you, no need for any imaginary points :) – N.B. May 20 '15 at 10:53

1 Answers1

2

From php.net:

The following things are considered to be empty:

"" (an empty string)
0 (0 as an integer)
0.0 (0 as a float)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
$var; (a variable declared, but without a value)

Every object you create won't be "empty".

stile17
  • 171
  • 8