What's the difference between if(!$variable) and if(isset($variable))?

前端 未结 3 1263
一个人的身影
一个人的身影 2020-12-06 11:16

What is the difference between if(!$variable) and if(isset($variable))?

相关标签:
3条回答
  • 2020-12-06 11:51

    If a variable is not set, then you will get a warning when using if(!Variable).

    0 讨论(0)
  • 2020-12-06 12:00

    They are two different statements

    1. in the first you check if a variable is false hence the '!'
    2. here you check if a variable is actually set to some value other then null.
    0 讨论(0)
  • 2020-12-06 12:03

    Well, the answer is pretty simple. isset($var) returns whether or not a variable exists and is not null, where !$var tells you if that variable is true, or anything that evaluates to true (such as a non-empty string). This is summarized in the first table of this documentation page.

    Also, using !$var will output a notice that you're using an undefined variable, whereas isset($var) won't do that.

    Mind you, they are two different things:

    <?php
    var_dump( isset($foo) ); // false.
    var_dump( !$foo );       // true, but with a warning.
    
    $foo = false;
    var_dump( isset($foo) ); // true
    var_dump( !$foo );       // true.
    
    0 讨论(0)
提交回复
热议问题