JudgmentVariable is empty, which is used on many occasions. At the same time, like many novices, I often make some mistakes, so I sorted out some commonly used judgment variables in PHP that determine whether the variable is empty. Method
1. isset function: Determine whether the variable is initialized
Description: It does not determine whether the variable is empty, and can be used to determine whether the array Whether the elements in
have been definedNote: When using isset to determine whether the array elements have been initialized, its efficiency is about 4 times higher than array_key_exists
$a = ''; $a['c'] = ''; if (!isset($a)) echo '$a 未被初始化' . ""; if (!isset($b)) echo '$b 未被初始化' . ""; if (isset($a['c'])) echo '$a 已经被初始化' . ""; // 显示结果为 // $b 未被初始化 // $a 已经被初始化
Description: Any uninitialized variable, the value is 0 or false or emptyString"" or null Variables, empty arrays, and objects without any attributes
will be judged as empty==true
Note 1: Uninitialized variables can also be detected as "empty" by empty "
$a = 0; $b = ''; $c = array(); if (empty($a)) echo '$a 为空' . ""; if (empty($b)) echo '$b 为空' . ""; if (empty($c)) echo '$c 为空' . ""; if (empty($d)) echo '$d 为空' . "";
Note: Variables and empty arrays with a value of 0 or false or empty string "" or null will be judged as null
$a = 0; $b = array(); if ($a == null) echo '$a 为空' . ""; if ($b == null) echo '$b 为空' . ""; if ($c == null) echo '$b 为空' . ""; // 显示结果为 // $a 为空 // $b 为空 // Undefined variable: c
Description: When the variable is assigned a value of "null", the detection result is true
Note 1: null is not case-sensitive: $a = null; $a = NULL There is no difference
Note 2: The detection result is true only when the value of the variable is "null", 0, empty string, Both false and empty arrays are detected as false
$a = null; $b = false; if (is_null($a)) echo '$a 为NULL' . ""; if (is_null($b)) echo '$b 为NULL' . ""; if (is_null($c)) echo '$c 为NULL' . ""; // 显示结果为 // $a 为NULL // Undefined variable: c
Note: When the variable is assigned a value of "null" and the type of the variable is also "null", the detection result is true
Note 1 : When it is judged as "null", equal to is_null has the same effect.
Summary: In PHP, "NULL" and "empty" " are 2 concepts.
isset is mainly used to determine whether a variable has been initialized.
empty can set variables with values of "false", "empty", "0", "NULL", and "uninitialized" Judged as TRUE
is_null Only variables with a value of "NULL" are judged as TRUE
var == null Judged as TRUE are variables with values of "false", "empty", "0", and "NULL"
The above is the detailed content of Summary of examples of methods to determine whether a variable is empty in PHP. For more information, please follow other related articles on the PHP Chinese website!