These variable judgment functions are actually used quite a lot in PHP development, and they all look similar at first glance, but in fact there are still many differences. If you are not sure, , maybe there will be some potential bugs left, including the fact that I have encountered such pitfalls myself. For example, once I encountered a problem with using empty to judge. The front end allows input of 0, but if I use empty to judge, it will not work. If it is true, I will report the error directly, so this judgment cannot be used here.
Recommended: "PHP Tutorial"
Let’s first look at the specific uses of these functions
isset — Detection Whether the variable has been set and non-NULL
empty - Check whether a variable is empty, the following things are considered empty
"" (empty string)
0 (0 as an integer)
0.0 (0 as a floating point number)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
$var; (a variable declared but without a value)
is_null — Detect variables Whether it is NULL
一isset
Determine whether the variable has been defined first, whether the key value of the array exists, etc.
$val){ echo $key . '=>' . var_dump(isset($val)) . "\r\n"; } //以上输出只有 null返回false,其它都为真 $arr = ['name' =>'lc', 'age' => 22, 'address' =>null]; echo isset($arr['name']) . "\r\n"; //true echo isset($arr['mobile'])."\r\n"; //false echo isset($arr['address']) ."\r\n"; //false //未定义的键和值为null,返回false
empty
$data=[""," ", 0, 0.0 ,"0", null, "null", true, false ,[]]; foreach ($data as $key => $val){ echo $key . '=>' . var_dump(empty($val)) . "\r\n"; } //以上输出 '" "',"null",true等为false,其它为true is_null $data=[""," ", 0, 0.0 ,"0", null, "null", true, false ,[]]; foreach ($data as $key => $val){ echo $key . '=>' . var_dump(is_null($val)) . "\r\n"; } //以上输出 null 为true,其它全为false
In addition, PHP7 has a quick way to judge which is the ?? and ?: syntax. You should also pay more attention to this
$a ?? 0; //相当于isset($a); $a ?: 0; //相当于!empty($a);
Through the above example, you should understand these few There is a difference. As long as we pay more attention during development, we can choose the appropriate judgment function.
Conclusion
##isset: All non-null values are true. empty: "", 0,0.0,"0", null, false, array(), undefined var are all true. is_null: The value is null and is true.For more PHP related knowledge, please visit
PHP Chinese website!
The above is the detailed content of Summary of usage of PHP isset(), is_null, empty(). For more information, please follow other related articles on the PHP Chinese website!