There are many ways to determine whether a variable is empty in PHP. Let’s take a look at each one.
1.isset function: determine whether the variable is initialized
Note: It does not determine whether the variable is empty, and can be used to determine whether the elements in the array have been defined.
注意:当使用isset来判断数组元素是否被初始化过时,它的效率比array_key_exists高4倍左右。
2. empty function: detect whether the variable is "empty"
Explanation : Any uninitialized variable, a variable with a value of 0 or false or an empty string "" or null, an empty array, or an object without any attributes will be judged as empty==true
注意1:未初始化的变量也能被empty检测为”空” 注意2:empty只能检测变量,而不能检测语句。
3. var == null Function: Determine whether the variable is "null"
Description: Variables and empty arrays with a value of 0 or false or "empty string" or null will be judged as null
注意:与empty的显著不同就是:变量未初始化时 var == null 将会报错。
4. is_null function: detect whether the variable is "null"
Description: When the variable is assigned a value of "null", the detection result is true
注意1:null不区分大小写:$a = null; $a = NULL 没有任何区别 注意2:仅在变量的值为”null”时,检测结果才为true,0、空字符串、false、空数组都检测为false 注意3:变量未初始化时,程序将会报错。
5. var = == null function: Detect whether the variable is "null", and the type of the variable must also be "null"
说明:当变量被赋值为”null”时,同时变量的类型也是”null”时,检测结果为true 注意1:在判断为”null”上,全等于和is_null的作用相同 注意2:变量未初始化时,程序将会报错。
In PHP, "NULL" and "empty" are two concepts.
isset is mainly used to determine whether a variable has been initialized.
empty can determine variables with values of "false", "empty", "0", "NULL", and "uninitialized" as TRUE
is_null only determines the variables with the value "NULL" as TRUE
var == null and determines the variables with the values "false", "empty", "0", and "NULL" as TRUE
var == = null Only variables with a value of "NULL" are judged as TRUE
Note: When judging whether a variable is really "NULL", is_null is mostly used to avoid interference from values such as "false" and "0".
The above is the detailed content of How to determine whether an object is empty in php. For more information, please follow other related articles on the PHP Chinese website!