isset vs empty vs is_null

PHP has multiple functions used to check PHP variables with respect to their initialized values. These functions are,

  • isset() is to check if a variable is set with a value.
  • empty() is to check if a given variable is empty. The difference with isset() is, isset has NULL check enabled.
  • is_null() – It is to check whether a variable is defined as NULL.

Ok! Now find the difference!

difference

I feel the effective way to communicate the difference would be with the help of a TRUTH TABLE,

  “” “apple” NULL FALSE 0 undefined
empty() TRUE FALSE TRUE TRUE TRUE TRUE
is_null() FALSE FALSE TRUE FALSE FALSE ERROR
isset() TRUE TRUE FALSE TRUE TRUE FALSE

Code to Understand the Difference

<?php

print "<br/>ISSET: <br/>";
$var = "";
print "isset():". isset($var)."<br/>";
$var = "apple";
print "isset('apple'):". isset($var)."<br/>";
$var = NULL;
print "isset('NULL'):". isset($var)."<br/>";
$var = FALSE;
print "isset('FALSE'):". isset($var)."<br/>";
$var = 0;
print "isset('0'):". isset($var)."<br/>";
print "isset(undefined):". isset($var3)."<br/>";

print "<br/>EMPTY: <br/>";
$var = "";
print "empty():". empty($var)."<br/>";
$var = "apple";
print "empty('apple'):". empty($var)."<br/>";
$var = NULL;
print "empty('NULL'):". empty($var)."<br/>";
$var = FALSE;
print "empty('FALSE'):". empty($var)."<br/>";
$var = 0;
print "empty('0'):". empty($var)."<br/>";
print "empty(undefined):". empty($var1)."<br/>";

print "<br/>IS_NULL: <br/>";
$var = "";
print "is_null():". is_null($var)."<br/>";
$var = "apple";
print "is_null('apple'):". is_null($var)."<br/>";
$var = NULL;
print "is_null('NULL'):". is_null($var)."<br/>";
$var = FALSE;
print "is_null('FALSE'):". is_null($var)."<br/>";
$var = 0;
print "is_null('0'):". is_null($var)."<br/>";
print "is_null(undefined):". is_null($var2)."<br/>";

?>

Output:

ISSET: isset():1 isset(‘apple’):1 isset(‘NULL’): isset(‘FALSE’):1 isset(‘0’):1 isset(undefined): EMPTY: empty():1 empty(‘apple’): empty(‘NULL’):1 empty(‘FALSE’):1 empty(‘0’):1 empty(undefined):1 IS_NULL: is_null(): is_null(‘apple’): is_null(‘NULL’):1 is_null(‘FALSE’): is_null(‘0’): Notice: Undefined variable: var2 in C:\xampp\htdocs\phppot_samples\php_isset\php_isset.php on line 40 is_null(undefined):1

This PHP code tutorial was published on October 4, 2013.

↑ Back to Top