The best practice for not null if statements

前端 未结 4 1716
你的背包
你的背包 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:34

    Rather than:

    if (!($error == NULL))
    

    Simply do:

    if ($error)
    

    One would think that the first is more clear, but it's actually more misleading. Here's why:

    $error = null;
    
    if (!($error == NULL)) {
        echo 'not null';
    }
    

    This works as expected. However, the next five values will have the same and (to many, unexpected) behavior:

    $error = 0;
    $error = array();
    $error = false;
    $error = '';
    $error = 0.0;
    

    The second conditional if ($error) makes it more clear that type casting is involved.

    If the programmer wanted to require that the value actually be NULL, he should have used a strict comparison, i.e., if ($error !== NULL)

    0 讨论(0)
  • 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.
    
    0 讨论(0)
  • 2021-02-13 16:53

    There are ways:

    <?php
    
    error_reporting(E_ALL);
    
    $foo = NULL;
    var_dump(is_null($inexistent), is_null($foo));
    
    ?>
    

    Another:

    <?php
    
    $var = '';
    
    // This will evaluate to TRUE so the text will be printed.
    if (isset($var)) {
        echo "This var is set so I will print.";
    }
    ?>
    

    To check if it's empty:

    <?php
    $var = 0;
    
    // Evaluates to true because $var is empty
    if (empty($var)) {
        echo '$var is either 0, empty, or not set at all';
    }
    
    // Evaluates as true because $var is set
    if (isset($var)) {
        echo '$var is set even though it is empty';
    }
    ?>
    
    0 讨论(0)
  • 2021-02-13 16:56

    Why just don't

    if (!$var)
    

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