Detecting insufficient PHP variables: FALSE vs NULL vs unset() vs empty()?

前端 未结 3 865
花落未央
花落未央 2021-01-07 10:35

What is the best way to define that a value does not exist in PHP, or is not sufficent for the applications needs.

$var = NULL, $var = array()

相关标签:
3条回答
  • 2021-01-07 10:54

    Another thing to remember is that since php is liberal in what it allows to evaluate to NULL or empty, it's necessary to use the identity operators (===, !== see http://php.net/operators.comparison. This is the reason why all of these comparison and equality functions exists, since you often have to differentiate between values with subtle differences.

    If you are explicitly checking for NULL, always use $var === NULL

    0 讨论(0)
  • 2021-01-07 11:04

    Each function you named is for different purposes, and they should be used accordingly:

    • empty: tells if an existing variable is with a value that could be considered empty (0 for numbers, empty array for arrays, equal to NULL, etc.).
    • isset($var): tells if the script encountered a line before where the variable was the left side of an assignment (i.e. $var = 3;) or any other obscure methods such as extract, list or eval. This is the way to find if a variable has been set.
    • $var == NULL: This is tricky, since 0 == NULL. If you really want to tell if a variable is NULL, you should use triple =: $var === NULL.
    • if($var): same as $var == NULL.

    As useful link is http://us2.php.net/manual/en/types.comparisons.php.

    The way to tell if the variable is good for a piece of script you're coding will entirely depend on your code, so there's no single way of checking it.

    One last piece of advice: if you expect a variable to be an array, don't wait for it to be set somewhere. Instead, initialize it beforehand, then let your code run and maybe it will get overwritten with a new array:

    // Initialize the variable, so we always get an array in this variable without worrying about other code.
    $var = array();
    
    if(some_weird_condition){
      $var = array(1, 2, 3);
    }
    
    // Will work every time.
    foreach($var as $key => $value){
    }
    
    0 讨论(0)
  • 2021-01-07 11:13

    My vote goes for unset(), because non existing variables should generate an notice when used.

    Testing gets a bit more complicated, because isset() wil be false if the variable is "not existings" or null. (Language designflaw if you'd ask me)

    You could use array_key_exists() for valiables in $GLOBALS, $_POST etc.
    For class properties there is property_exists().

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