Posted by: phillipnb | May 13, 2012

PHP empty() function


I think one of the most misunderstood function in php is the empty(). The definition for empty in the manual is that it is used to determine whether a variable is empty. But developers often use it vaguely and the end result is often failure of a critical application. For example. If a developer were to decide branching of a logic inside a piece of code based on the count returned from a database table like this:

if (empty($count) === FALSE && $count == 0)
{
    // do something
}
else
{
	//do something else
}

The author of the above piece of code was hoping that when the count is zero, then the if part will get executed, otherwise the else part should get executed. But in the above case, always the else part will get executed. Why?. If the variable stores zero, then empty() will return boolean true and the above IF part will never evaluate to true and hence always the else part will get executed. This is a trick that every developer should be aware of.

Take a look at a few other examples:

$var1 = NULL;
$var2 = '';
$var3 = 100;
$var4 = 'A';
$var5 = '20';
$var6 = array(1,2,3);
$var7 = array();
$var8 = 0;
$var9 = FALSE;

var_dump(empty($var1));
var_dump(empty($var2));
var_dump(empty($var3));
var_dump(empty($var4));
var_dump(empty($var5));
var_dump(empty($var6));
var_dump(empty($var7));
var_dump(empty($var8));
var_dump(empty($var9));
var_dump(empty($var10));

and the output for these will be:

bool(true)
bool(true)
bool(false)
bool(false)
bool(false)
bool(false)
bool(true)
bool(true)
bool(true)
bool(true)

As you can see, if a variable is storing boolean false, a zero, a null( not a blank space), an empty array or if the variable is not defined then empty() will always return a boolean true.

Happy PHP Programming


Responses

  1. This is a comment to the admin. I came to your “Be careful with the empty() My Experience with PHP” page via Google but it was difficult to find as you were not on the front page of search results. I see you could have more visitors because there are not many comments on your site yet. I have found a website which offers to dramatically increase your rankings and traffic to your website: http://www.linklegends.com/free-trial. I managed to get close to 1000 visitors/day using their services, you could also get lot more targeted traffic from search engines than you have now. Their free trial and brought significantly more visitors to my site. Hope this helps 🙂 Take care.


Leave a comment

Categories