English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Usage and Differences of empty, isset, and is_null in PHP

1.empty usage

bool empty ( mixed var)
If var is a non-empty or non-zero value, empty() returns FALSE. In other words, "", 0, "0", NULL, FALSE, array(), var $var; and objects with no properties will be considered empty, and TRUE will be returned if var is empty

2.isset()

isset -- Check if a variable is set

Description
bool isset ( mixed var [, mixed var [, ...]])
Returns TRUE if var exists, otherwise returns FALSE.
After a variable has been released using unset(), it will no longer be isset(). If isset() is used to test a variable set to NULL, it will return FALSE. It should also be noted that a NULL byte ("0") is not equivalent to PHP's NULL constant.

Note: If a variable does not exist, both isset() and empty() will not report an error; is_null() and is_numeric() will report an error

How to distinguish among the three elements [0, '', null] in the following array? (1)difference 0:

$a = 0;
isset($a) && is_numeric($a) === true

(2)difference ''

$a = '';
empty($a) && $a=== ''

(3)difference null

$a = null;
is_null($a);  

Additionally, when submitting a form, it is often necessary to check if a variable exists, for example, if $_REQUEST['status'] = 0; using empty($_REQUEST['status']) returns true, but using isset($_REQUEST['status']) to judge is not empty

3. is_null():

bool is_null ( mixed $var ) (php.net official document function definition)
When the parameter meets the following three conditions, is_null() will return TRUE, otherwise it will return FALSE
1、it is assigned a value of NULL
2、it has not been assigned a value
3、it is undefined, which is equivalent to unset(), after a variable is unset(), is it not undefined
Let's look at some examples:

$myvar = NULL;  
var_dump(is_null($myvar)); // TRUE 
$myvar1;      
var_dump(is_null($myvar1)); // TRUE Notice: Undefined variable 
$num = 520; 
unset($num); 
var_dump(is_null($num)); //TRUE Notice: Undefined variable 
var_dump(is_null($some_undefined_var)); //TRUE Notice: Undefined variable 
$myvar = 0; is_null($myvar);   // FALSE 
$myvar = FALSE; is_null($myvar); // FALSE 
$myvar = ''; is_null($myvar);  // FALSE 
You May Also Like