This a few variable judgment function in PHP is much used in the development, and coarse looks about the same, but there are still a lot of difference, if don’t know, maybe would have left some potential bugs, including myself, also met such pit, such as once I met with the empty judge the problem, the front end is allowed to enter 0, But if I use empty, it will be true, and I will directly report an error, so I can’t use this judgment here.

So let’s look at what these functions actually do

Isset – checks if the variable isset and not NULL

Empty – Checks if a variable is empty, everything below is considered empty “” (empty string) 0 (as an integer 0) 0.0 (as a floating point 0) “0” (as a string 0) NULL array() (an empty array) $var; (a variable that is declared but has no value)

Is_null – Checks whether the variable is NULL

A isset

Check whether a variable is defined first, whether an array key exists, etc


      
$data=[""."".0.0.0 ,"0".null."null".true.false[]];foreach ($data as $key => $val){
	echo $key . '= >' . var_dump(isset($val)) . "\r\n";
}
// The output above only returns false with null, all else is true

$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
// Undefined key and value are null, return false
Copy the code

empty

$data=[""."".0.0.0 ,"0".null."null".true.false[]];foreach ($data as $key => $val){
	echo $key . '= >' . var_dump(empty($val)) . "\r\n";
}
// Output '" "', "null",true, etc., false, others true
Copy the code

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 is true for the above output, false for all others
Copy the code

In addition, PHP7 has a quick way to determine?? And? : Syntax, pay more attention to this too

$a ?? 0; // equivalent to isset($a);$a ? :0; // equivalent to! empty($a);
Copy the code

From the examples above, we should understand the differences between these several, and we just need to pay more attention during development, can choose the appropriate judgment function.

conclusion

Isset: all non-null entries are true.

Empty: “”,0,0.0,”0″,null,false,array(), undefined var is true.

Is_null: The value is null and true.