Null and Empty Strings

Before I actually start, here’s a little quiz. Is null equivalent to “” ? If you said yes, you definitely need to go through this article, and even if you know that “” is an empty string and not equivalent to NULL, you might want to run through the article.

Let’s start by talking about this concept in the context of PHP. The definition of null for PHP goes like this: “The special NULL value represents that a variable has no value. NULL is the only possible value of type NULL.”

Note: The null type was introduced in PHP 4.

A variable is considered to be NULL if


  • it has been assigned the constant NULL.


  • it has not been set to any value yet.


  • it has been unset().


Furthermore, there is only one value of type NULL, and that is the case-insensitive keyword NULL.



$var = NULL;



Possible cases where you may misunderstand this and run into problems are:


  1. $var is an empty string


$var = “” ;

$z = is_null($var) ;

return $z ; // returns false




$var = ” ;

$z = is_null($var) ;

return $z ; // returns false



  1. $var is an empty array


$var = array() ;

$z = is_null($var) ;

return $z ; // returns false


The cases where null behaves as it is intended to are:

$var = null ; // case is not a problem – NULL, null, Null ..are all same

$z = is_null($var) ;

return $z ; // returns true


// $var is undefined or unset or uninitialized

$z = is_null($var) ;

return $z ; // returns true


In most cases we are used to displaying the contents of $var in “if” style i.e.,


if ( $var ) { // returns true when var has value and $var is not equal to zero

echo $var ; // or do some processing



This way of coding has a problem: whenever $var has zero value, it will not return true. To escape this predicament, sometimes one uses is_null(), which again causes the problems I already listed above.

By Rz Rasel Posted in Php

2 comments on “Null and Empty Strings

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s