isset and empty in PHP

05 Jun 2017 in PHP

Sometimes you may be in confusion about the proper use of isset and empty functions in PHP when testing for the existence of a variable, array key or object property.

For these two functions, the PHP manual states:

isset: Determine if a variable is set and is not NULL. If multiple parameters are supplied then isset() will return TRUE only if all of the parameters are set. Evaluation goes from left to right and stops as soon as an unset variable is encountered.

empty: Determine whether a variable is considered to be empty. A variable is considered empty if it does not exist or if its value equals FALSE. empty() does not generate a warning if the variable does not exist.

Because the check for NULL in isset is using the identity comparison (===), while in empty the equality comparison (==) is used, it may sometimes lead to unexpected behaviour from a programmer's point of view.

My preference in general is to use empty (which can be seen as a shorthand for !isset($var) || !$var) and use isset when trying to access keys in arrays or properties in objects.

As an example, look at the following:

                            | isset() | empty() |
$foo                        | false   | true    |
$null        = null;        | false   | true    |
$false       = false;       | true    | true    |
$true        = true;        | true    | false   |
$emptyString = "";          | true    | true    |
$arr         = [];          | true    | true    |
$array       = ['k'=>'v'];  | true    | false   |
               $array['k']  | true    | false   |
               $array['X']  | false   | true    |