check if variable empty

前端 未结 12 1218
旧时难觅i
旧时难觅i 2020-11-27 14:00
if ($user_id == NULL || $user_name == NULL || $user_logged == NULL) {
    $user_id = \'-1\';
    $user_name = NULL;
    $user_logged = NULL;
}
if ($user_admin == NUL         


        
相关标签:
12条回答
  • 2020-11-27 14:16

    here i have explained how the empty function and isset works please use the one that is appropriate also you can use is_null function also

    <?php
        $val = 0;
        //evaluates to true because $var is empty
        if (empty($val)) {
            echo '$val is either 0, empty, or not set at all';
        }
        //evaluates to true because $VAR IS SET
        if (isset($val)) {
            echo '$val is set even though it is empty';
        }
        ?>
    
    0 讨论(0)
  • 2020-11-27 14:16
    <?php
    
    $nothing = NULL;
    $something = '';
    $array = array(1,2,3);
    
    // Create a function that checks if a variable is set or empty, and display "$variable_name is SET|EMPTY"
    function  check($var) {
        if (isset($var)) {
            echo 'Variable is SET'. PHP_EOL;
      } elseif (empty($var)) { 
            echo 'Variable is empty' . PHP_EOL;
    
       } 
    
    } 
    
    check($nothing);
    check($something);
    check($array);
    
    0 讨论(0)
  • 2020-11-27 14:17

    you can use isset() routine .

    also additionaly you can refer an range of is_type () functions like

    is_string(), is_float(),is_int() etc to further specificaly test

    0 讨论(0)
  • 2020-11-27 14:20

    Felt compelled to answer this because of the other responses. Use empty() if you can because it covers more bases. Future you will thank me.

    For example you will have to do things like isset() && strlen() where instead you could use empty(). Think of it like this empty is like !isset($var) || $var==false

    0 讨论(0)
  • 2020-11-27 14:23

    Its worth noting - and I only found this out after nearly 9 years of PHP coding that the best way of checking any variable exists is using the empty() function. This is because it doesn't generate errors and even though you turn them off - PHP still generates them! empty() however won't return errors if the variable doesn't exist. So I believe the correct answer is not to check if its null but to do the following

    if (!empty($var) && is_null($var))
    

    Note the PHP manual

    variable is considered empty if it does not exist or if its value equals FALSE

    As opposed to being null which is handy here!

    0 讨论(0)
  • 2020-11-27 14:27

    The best and easiest way to check if a variable is empty in PHP is just to use the empty() function.

    if empty($variable) then ....

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