Why check both isset() and !empty()

后端 未结 10 2505
难免孤独
难免孤独 2020-11-21 23:48

Is there a difference between isset and !empty. If I do this double boolean check, is it correct this way or redundant? and is there a shorter way

相关标签:
10条回答
  • 2020-11-22 00:05

    Empty just check is the refered variable/array has an value if you check the php doc(empty) you'll see this things are considered emtpy

    * "" (an empty string)
    * 0 (0 as an integer)
    * "0" (0 as a string)
    * NULL
    * FALSE
    * array() (an empty array)
    * var $var; (a variable declared, but without a value in a class)
    

    while isset check if the variable isset and not null which can also be found in the php doc(isset)

    0 讨论(0)
  • 2020-11-22 00:05
    • From the PHP Web site, referring to the empty() function:

    Returns FALSE if var has a non-empty and non-zero value.

    That’s a good thing to know. In other words, everything from NULL, to 0 to “” will return TRUE when using the empty() function.

    • Here is the description of what the isset() function returns:

    Returns TRUE if var exists; FALSE otherwise.

    In other words, only variables that don’t exist (or, variables with strictly NULL values) will return FALSE on the isset() function. All variables that have any type of value, whether it is 0, a blank text string, etc. will return TRUE.

    0 讨论(0)
  • 2020-11-22 00:12

    This is completely redundant. empty is more or less shorthand for !isset($foo) || !$foo, and !empty is analogous to isset($foo) && $foo. I.e. empty does the reverse thing of isset plus an additional check for the truthiness of a value.

    Or in other words, empty is the same as !$foo, but doesn't throw warnings if the variable doesn't exist. That's the main point of this function: do a boolean comparison without worrying about the variable being set.

    The manual puts it like this:

    empty() is the opposite of (boolean) var, except that no warning is generated when the variable is not set.

    You can simply use !empty($vars[1]) here.

    0 讨论(0)
  • 2020-11-22 00:17

    It is not necessary.

    No warning is generated if the variable does not exist. That means empty() is essentially the concise equivalent to !isset($var) || $var == false.

    php.net

    0 讨论(0)
  • 2020-11-22 00:18
    $a = 0;
    if (isset($a)) { //$a is set because it has some value ,eg:0
        echo '$a has value';
    }
    if (!empty($a)) { //$a is empty because it has value 0
        echo '$a is not empty';
    } else {
        echo '$a is empty';
    }
    
    0 讨论(0)
  • 2020-11-22 00:20

    The accepted answer is not correct.

    isset() is NOT equivalent to !empty().

    You will create some rather unpleasant and hard to debug bugs if you go down this route. e.g. try running this code:

    <?php
    
    $s = '';
    
    print "isset: '" . isset($s) . "'. ";
    print "!empty: '" . !empty($s) . "'";
    
    ?>
    

    https://3v4l.org/J4nBb

    0 讨论(0)
提交回复
热议问题