PHP: empty(), is_null() and isset() comparison

The subtle differences between empty(), is_null() and isset() are common source of confusion and uncertainty.  So in this post I’ll try and clarify how these three (boolean) functions work.


var $x;

empty($x) // TRUE
is_null($x) // TRUE
isset($x) // FALSE

This is probably what you’d expect. If you declare a variable but don’t assign a value, clearly it’s empty and also NULL. isset() returns FALSE because the variable is NULL.


$x = NULL;

empty($x) // TRUE
is_null($x) // TRUE
isset($x) // FALSE

As you can see, this is exactly the same as the example above except you’re “manually” setting the variable to NULL. The variable is still empty and it is still NOT SET.


$x = "";

empty($x) // TRUE
is_null($x) // FALSE
isset($x) // TRUE

If we assign the variable a string- even if it consists of 0 characters- the variable is said to be set. And if the variable is set, is can’t be NULL. However because the string is made up of 0 characters, the variable is empty.


$x = array();

empty($x) // TRUE
is_null($x) // FALSE
isset($x) // TRUE

Similarly if we look at this example, the variable is set and not NULL, because we’re assigning an array to it. But because the array is empty- it has no elements in it- the variable is therefore empty.


$x = FALSE;

empty($x) // TRUE
is_null($x) // FALSE
isset($x) // TRUE

For the third time in a row, we have the same outcomes. The variable is set and therefore not NULL. But a variable that’s simply assigned FALSE, must be empty.

This entry was posted in PHP and web. Bookmark the permalink.

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>