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

前端 未结 3 886
花落未央
花落未央 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 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){
    }
    

提交回复
热议问题