Exclamation mark in front of variable - clarification needed

33,428

Solution 1

if(! $a) is the same as if($a == false). Also, one should take into account that type conversion takes place when using == operator.
For more details, have a look into "Loose comparisons with ==" section here. From there it follows, that for strings "0" and "" are equal to FALSE ( "0"==false is TRUE and ""==false is TRUE, too).

Regarding posted examples:
Example 1
It will work, but you should note, that both "0" and "" are 'empty' strings.

Example 2
It will work

Solution 2

The ! negates. true becomes false, and anything that evaluated to false becomes true.

If you're writing PHP and you don't know all the operators by heart.. you should not write a single line of code until you know them by heart:

http://php.net/manual/en/language.operators.php

These are absolute basics.

Solution 3

It's a boolean tester. Empty or false.

Solution 4

It's the not boolean operator, see the PHP manual for further detail.

Share:
33,428
aborted
Author by

aborted

Updated on July 12, 2022

Comments

  • aborted
    aborted almost 2 years

    I've been working with PHP for quite a while now, but this was always a mystery to me, the correct use of the exclamation mark (negative sign) in front of variables.

    What does !$var indicate? Is var false, empty, not set etc.?

    Here are some examples that I need to learn...

    Example 1:

    $string = 'hello';
    $hello = (!empty($string)) ? $string : '';
    
    if (!$hello)
    {
        die('Variable hello is empty');
    }
    

    Is this example valid? Would the if statement really work if $string was empty?

    Example 2:

    $int = 5;
    $count = (!empty($int)) ? $int : 0;
    
    // Note the positive check here
    if ($count)
    {
       die('Variable count was not empty');
    }
    

    Would this example be valid?

    I never use any of the above examples, I limit these if ($var) to variables that have boolean values only. I just need to know if these examples are valid so I can broaden the use of the if ($var) statements. They look really clean.

    Thanks.

  • aborted
    aborted over 11 years
    Finally someone that actually understood what I meant. The table Comparisons of $x with PHP functions answered my question. From there we can understand that $x = "php"; then if($x) would be true. Those who said that I need to learn basic stuff, please try to read the question carefully next time and first understand what I'm asking. Don't rush to put an answer that isn't actually answering my (or someone else's) question. Thanks a lot bhovhannes.