check if variable empty

前端 未结 12 1217
旧时难觅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:02

    1.

    if(!($user_id || $user_name || $user_logged)){
        //do your stuff
    }
    

    2 . No. I actually did not understand why you write such a construct.

    3 . Put all values into array, for example $ar["user_id"], etc.

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

    Please define what you mean by "empty".

    The test I normally use is isset().

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

    You can check if it's not set (or empty) in a number of ways.

    if (!$var){ }
    

    Or:

    if ($var === null){ } // This checks if the variable, by type, IS null.
    

    Or:

    if (empty($var)){ }
    

    You can check if it's declared with:

    if (!isset($var)){ }
    

    Take note that PHP interprets 0 (integer) and "" (empty string) and false as "empty" - and dispite being different types, these specific values are by PHP considered the same. It doesn't matter if $var is never set/declared or if it's declared as $var = 0 or $var = "". So often you compare by using the === operator which compares with respect to data type. If $var is 0 (integer), $var == "" or $var == false will validate, but $var === "" or $var === false will not.

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

    empty() is a little shorter, as an alternative to checking !$user_id as suggested elsewhere:

    if (empty($user_id) || empty($user_name) || empty($user_logged)) {
    }
    
    0 讨论(0)
  • 2020-11-27 14:09

    If you want to test whether a variable is really NULL, use the identity operator:

    $user_id === NULL  // FALSE == NULL is true, FALSE === NULL is false
    is_null($user_id)
    

    If you want to check whether a variable is not set:

    !isset($user_id)
    

    Or if the variable is not empty, an empty string, zero, ..:

    empty($user_id)
    

    If you want to test whether a variable is not an empty string, ! will also be sufficient:

    !$user_id
    
    0 讨论(0)
  • 2020-11-27 14:13

    To check for null values you can use is_null() as is demonstrated below.

    if (is_null($value)) {
       $value = "MY TEXT"; //define to suit
    }
    
    0 讨论(0)
提交回复
热议问题