Value Checking in PHP with isset() and empty()

PHP has several functions which can be used to determine certain things about the value of a variable. None of these functions are particularly complex, but they can be difficult to tell apart – for instance, when to use empty()versus isset().
The PHP Doc site has a Type Comparison Table demonstrating the result you get from these comparison functions based on several different values. This table serves as a great reference to find out which function is designed to provide the kind of comparison you need.
For this post, I want to focus on three specific ways of checking values. Considering the following:
$nullvar;
$setvar = "we are set.";
$setbutfalse = false;

What happens when you run isset(), empty(), or if() on each of these variables? Here are some pointers:
isset()
  • isset() returns true if a variable is set, no matter what its contents. The contents may be: false, 0, ”, or anything else, and isset() will still return true. So long as the variable has had some value set, it will be true. There is one exception.
  • isset() returns false if a variable has never been set or if a variable has been assigned the specific keyword NULL (i.e., $var = NULL;).
  • For the above variables, isset($nullvar) will be false; isset($setvar) will be true; isset($setbutfalse) will be true.
empty()
  • empty() returns true for any variable that is not set, contains no value, or contains a value that equals zero (such as 0, “0″, false, etc).
  • For the above variables, empty($nullvar) will be true; empty($setvar) will be false; empty($setbutfalse) will be true.
if()
  • if($var) does essentially the opposite of empty($var). When checking a variable with if($var), it will return true if the variable is set and contains some value other than zero/false.
  • For the above variables, if ($nullvar) will be false; if ($setvar) will be true; if ($setbutfalse) will be false.
When to use which? It depends on what you are trying to do.
  • If you want to see if a variable is set, period, and don’t care what its value is, use isset().
  • If you want to see if a variable is empty or contains a value that equals 0 or false, use empty().
  • If you want to see if a variable is not empty and does not contain a false/zero value, use !empty(). For example, if (!empty($passed)).
  • For the above example, you could also use if ($passed) and it would do the same thing.
Perhaps this post helps clear a little of the fog. Perhaps it just makes the fog thicker. Either way, it shows that PHP has a lot of little tools to meet a lot of use cases. In PHP, there are many ways to skin a cat. The trick is knowing which way is best.
Ref: http://croberts.me/2011/12/26/value-checking-in-php-with-isset-and-empty/ 

Comments

Popular Posts