Isset() of PHP is_ Do you understand?


In fact, these variable judgment functions are widely used in PHP development, and they all look almost the same. However, there are still many differences between them. If you don’t know them clearly, some potential bugs may be left behind, For example, once I encountered a problem with empty judgment. The front-end allowed to enter 0, but if I used empty judgment, it was true, and I directly reported an error, so I can’t use this judgment here.

Let’s take a look at the specific uses of these functions

Isset – detects whether the variable is set and is notNULL

Empty – checks if a variable is empty. The following are considered null
“(empty string)
0 (0 as an integer)
0.0 (as 0 of floating point number)
“0” (as 0 of string)
Array () (an empty array)
$VaR; (a variable that is declared but has no value)

Is_ Null – detects whether the variable is null

– isset

Judge whether the variable has been defined first, whether the key value of the array exists, etc

    echo $key . '=>' . var_dump(isset($val)) . "\r\n";
//The above output only returns null and returns false. The others are 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


$data=[""," ", 0, 0.0 ,"0", null, "null", true, false ,[]];
foreach ($data as $key => $val){
    echo $key . '=>' . var_dump(empty($val)) . "\r\n";
//The above outputs' "'," null ", true, etc. are false, others are true


$data=[""," ", 0, 0.0 ,"0", null, "null", true, false ,[]];
foreach ($data as $key => $val){
    echo $key . '=>' . var_dump(is_null($val)) . "\r\n";
//The above output null is true, others are all false

In addition, php7 has a quick way to judge: syntax, which should be paid more attention to

$a?? 0; // equivalent to isset ($a);
$a?: 0; // equivalent to! Empty ($a);

Through the above example, we should understand the differences between these several. In the development, we only need to pay more attention to select the appropriate judgment function.


Isset: all non null are true
Empty: “0, 0.0,” 0 “, null, false, array(), undefined VaR is true
Is_ Null: the value of null is true