if (!$variable)
tests if $variable
evaluates to false
. According to the chapter Converting to boolean, a lot of things evaluate to 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
- the special type NULL (including unset variables)
- SimpleXML objects created from empty tags
Therefore, using this kind of code to test if a variable is already set is dangerous. Also, it will generate notices when the variable is used but not set.
Yes, the code will execute with PHP 4. But you may get unexpected results when $variable
is set to 0
, the empty string or the string '0'
.
For cleaner code, you should use isset:
if (!isset($variable)) {
// for example...
$variable = "test";
}
According to the documentation, isset
was introduced with PHP 4.