PHP check if False or Null

Viewed 78740

I also get confused how to check if a variable is false/null when returned from a function.

When to use empty() and when to use isset() to check the condition ?

7 Answers

It is important to use the correct function / notation, not just whatever appears to work correctly. There are a few things to consider that are not mentioned in the existing answers.

  • Use isset to check if a variable has either not been set or has been set to null.
  • Use empty to check if a variable == false. null is cast to false and as with isset, no notice is thrown if the variable has not been set.

if (!$variable) or if ($variable == false) is the same as empty, except that a notice will be thrown if the variable has not been set.

if ($variable !== null) is the same as isset, except that a notice will be thrown if the variable has not been set.

NB

if (!$variable) and if ($variable !== null) perform better than their respective functions but not when notices are being generated, therefore, $variable needs to have been set. Don't suppress notices as a micro-optimisation, as this will make your code harder to debug and even suppressed notices cause a performance penalty.

Coalescing operators

If you are checking a variable so that you can assign a value to it, then you should use ??, ?: instead of if statements.

??

?? assigns a value when not equal to null. $variable = $a ?? $b is the same as:

if (isset($a))
    $variable = $a;
else
    $variable = $b;

?:

?: assigns a value when not == to false. $variable = $a ?: $b is the same as:

if ($a)
    $variable = $a;
else
    $variable = $b;

but remember that a notice will be generated when $a has not been set. If $a might not have been set, you can use $variable = !empty($a) ? $a : $b; instead.

Related