PHP: empty() is your friend

The right question is: Is it empty?

It’s easy to miss things that are very obvious, this is the proper way to check that a variable has a value that is not nothing (null, 0, FALSE, “false”, array(), etc) without getting PHP E_NOTICE messages (that I encourage you to show when developing):

// Check that $var is set and is not empty:

// 1. The WRONG way
if($var){
  // ... 
}

// 2. The LONG way
if(isset($var) && $var){
  // ...
}

// 3. The I ROCK way
if(!empty($var)){
  // ...
}

Leave a Reply

Your email address will not be published. Required fields are marked *