What's the difference? empty() vs. isset() PHP functions

(I thought this would provide the perfect opportunity to try out my recently-installed google-code-prettify Drupal module.)

Many coders consider empty() and isset() to be interchangeable (if reversed) functions, but there is one huge difference: empty($var) checks for whether $var is set and whether $var evaluates to TRUE.

The empty() function allows you to kill two birds with one stone. Rather than checking two conditions on $var to avoid PHP warnings…

<?php
if (isset($var) && $var) {
  // $var is set, and evaluates to true.
}
?>

…you can simply check one condition:

<?php
if (!empty($var)) {
  // $var is set, and evaluates to true.
}
?>

This is because empty() returns TRUE if $var is:1

The empty() function, then, is somewhat of a Swiss army knife for checking variables. I often use it to check flag variables, e.g.:

<?php
if (empty($field->required)) {
  // The field isn't required.
} else {
  // The field is required.
}
?>

In the above example, I use empty() to check the required property of a given field, even if it hasn’t been defined. (Note that even $field can be undefined, and no warning will be generated!) That’s what makes empty() so useful: it allows me to bypass all the isset()s and skip straight to the variable evaluation.2

  1. PHP manual: empty()
  2. Keep in mind that, in the $field example, the field is not required by default. This is because empty() evaluates to TRUE if $field->required is equal to FALSE or if $field->required is not set. If your use case expects that the field is required by default, it would be better to change the required property to be called "optional" (i.e., the opposite of "required") so that the evaluation logic would be reversed.