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
- undeclared
- declared but unset
- an empty array
- equal to any of the following:
0
,0.0
,'0'
,''
,NULL
,FALSE
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
- PHP manual: empty()
- Keep in mind that, in the
example, the field is not required by default. This is because$field
evaluates to TRUE ifempty()
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.$field->required