The best practice for not null if statements

前端 未结 4 1801
你的背包
你的背包 2021-02-13 16:32

I\'ve been writing my \"If this variable is not empty\" statements like so:

if ($var != \'\') {
// Yup
}

But I\'ve asked if this is correct, it

4条回答
  •  南笙
    南笙 (楼主)
    2021-02-13 16:49

    It is good to know exactly what is in your variable, especially if you are checking for uninitialized vs null or na vs true or false vs empty or 0.

    Therefore, as mentioned by webbiedave, if checking for null, use

    $error !== null
    $error === null
    is_null($error)
    

    if checking for initilized, as shibly said

    isset($var)
    

    if checking for true or false, or 0, or empty string

    $var === true
    $var === 0
    $var === ""
    

    I only use empty for ''s and nulls since string functions tend to be inconsistent. If checking for empty

    empty($var)
    $var  // in a boolean context
    
    // This does the same as above, but is less clear because you are 
    // casting to false, which has the same values has empty, but perhaps
    // may not one day.  It is also easier to search for bugs where you
    // meant to use ===
    $var == false
    

    If semantically uninitialized is the same as one of the values above, then initialize the variable at the beginning to that value.

    $var = ''
    ...  //some code
    
    if ($var === '') blah blah.
    

提交回复
热议问题