Monday, 16 July 2018

PHP isset() vs empty() vs is_null()

PHP isset() vs empty() vs is_null()

isset() and empty() are often viewed as functions that are opposite, however this is not always true. In this post I will explain the differences between these functions.

isset()

isset — Determine if a variable is set and is not NULL
In other words, it returns true only when the variable is not null.

empty()

empty — Determine whether a variable is empty
In other words, it will return true if the variable is an empty string, false, array(), NULL, “0?, 0, and an unset variable.

is_null()

is_null — Finds whether a variable is NULL
In other words, it returns true only when the variable is null. is_null() is opposite of isset(), except for one difference that isset() can be applied to unknown variables, but is_null() only to declared variables.
The table below is an easy reference for what these functions will return for different values. The blank spaces means the function returns bool(false).
Value of variable ($var)isset($var)empty($var)is_null($var)
“” (an empty string)bool(true)bool(true)
” ” (space)bool(true)
FALSEbool(true)bool(true)
TRUEbool(true)
array() (an empty array)bool(true)bool(true)
NULLbool(true)bool(true)
“0” (0 as a string)bool(true)bool(true)
0 (0 as an integer)bool(true)bool(true)
0.0 (0 as a float)bool(true)bool(true)
var $var; (a variable declared, but without a value)bool(true)bool(true)
NULL byte (“\ 0”)bool(true)
I have tested the above values in following PHP versions:
  • PHP 7.0.9
  • PHP 5.6.19
  • PHP 5.5.33

0 comments:

Post a Comment