Differences and Application Examples of empty isset and isnull in PHP

  • 2021-12-04 18:23:25
  • OfStack

When doing php development, you usually use empty , isset , is_null These functions, if used improperly, even bring some security risks to their own programs, bug. Most of the time, isset and empty are almost the same. Therefore, when developing, I didn't pay attention to it. When 1 paragraph is used as a process judgment, bug problem appears. Let's introduce the differences and uses of these three functions in 1 respectively.

empty

If the variable is a non-null or non-zero value, the empty() Returns FALSE. In other words, "", "0," 0 ", NULL, FALSE, array (), var $var, undefined; And objects without any attributes are considered empty, and TRUE is returned if var is empty. Code example:


$a = 0;
$b = '';
$c = array();
if (empty($a)) echo '$a  Empty ' . "";
if (empty($b)) echo '$b  Empty ' . "";
if (empty($c)) echo '$c  Empty ' . "";
if (empty($d)) echo '$d  Empty ' . "";
//  All the above outputs are empty 

isset

Returns TRUE if the variable exists (non-NULL), or FALSE (including undefined). The value of the variable is set to: null, and false is returned; after unset1 variables, the variable is canceled. Note that isset has special treatment for NULL value variables. Code example:


$a = '';
$a['c'] = '';
if (!isset($a)) echo '$a  Not initialized ' . "";
if (!isset($b)) echo '$b  Not initialized ' . "";
if (isset($a['c'])) echo '$a  Has been initialized ' . "";
//  Displays the result as 
// $b  Not initialized 
// $a  Has been initialized 

is_null

Checks if the passed-in value "value, variable, expression" is null. It returns TRUE only if one variable is defined and its value is null. Everything else returns FALSE "Error occurs when undefined variables are passed in!"


$a = null;
$b = false;
if (is_null($a)) echo '$a  For NULL' . "";
if (is_null($b)) echo '$b  For NULL' . "";
if (is_null($c)) echo '$c  For NULL' . "";
//  Displays the result as 
// $a  For NULL
// Undefined variable: c

Summarize


Related articles: