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

2019-03-15 01:40发布

问题:

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
}

回答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.



回答2:

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



回答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).