phpoperatorsnot-operator

What does if (!$variablename) do in PHP?


I know that != is "not equal", but what does it mean when you have this:

if(!$something)

My first guess is something to do with exceptions, but a look around google did not return anything.

So what does this do?


Solution

  • Whatever is in the variable is converted to a Boolean (the variable itself of course remains intact), and then a NOT operation (!) is done on the resulting Boolean. The conversion will happen because ! is a Logical Operator and only works on Boolean values.

    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

    Tip: If the variable is not expected to be Boolean, you might want to use something more specific like isset($variable), empty($variable), $variable === '', etc. depending on what you want to check for. Check the manual for details.