PHP: if (!$val) VS if (empty($val)). Is there any difference?

10,387

Solution 1

Have a look at the PHP type comparison table.

If you check the table, you'll notice that for all cases, empty($x) is the same as !$x. So it comes down to handling uninitialised variables. !$x creates an E_NOTICE, whereas empty($x) does not.

Solution 2

If you use empty and the variable was never set/created, no warning/error will be thrown.

Solution 3

Let see:

empty documentation:

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 $var; (a variable declared, but without a value in a class)

Booleans documentation:

When converting to boolean, the following values are considered FALSE:

  • the boolean FALSE itself
  • the integer 0 (zero)
  • the float 0.0 (zero)
  • the empty string, and the string "0"
  • an array with zero elements
  • an object with zero member variables (PHP 4 only)
  • the special type NULL (including unset variables)
  • SimpleXML objects created from empty tags

It seems the only difference (regarding the resulting value) is how a SimpleXML instance is handled. Everything else seems to give the same result (if you invert the boolean cast of course).

Share:
10,387

Related videos on Youtube

Bachx
Author by

Bachx

Updated on June 04, 2022

Comments

  • Bachx
    Bachx almost 2 years

    I was wondering what's the difference the two cases below, and which one is recommended?

    $val = 0;
    
    if (!$val) {
      //True
    }
    
    if (empty($val) {
      //It's also True
    }
    
  • rockerest
    rockerest over 12 years
    +1. Also note that this is the same as != [boolean result of evaluating $val], so the last column of the first table is mostly what you should be looking at.
  • Jason McCreary
    Jason McCreary over 12 years
    So what's the conclusion? From the list, boolean seems like the more robust check...
  • Bachx
    Bachx over 12 years
    Thanks, that's what I needed to know. So I guess empty($x) is the safer approach. I assume the difference is negligible performance wise right?
  • xdazz
    xdazz over 12 years
    Please note that when using empty() on inaccessible object properties, the __isset overloading method will be called, if declared.
  • Mark Amery
    Mark Amery almost 9 years
    This is incorrect. A quick test at the PHP shell reveals that empty handles empty SimpleXMLElement instances just like ! does; it's simply an error in the empty documentation that they aren't mentioned there.
  • leonbloy
    leonbloy about 5 years
    Gotta love the duplication of doc.