DEV Community

spO0q πŸ’πŸŽƒ
spO0q πŸ’πŸŽƒ

Posted on • Updated on

PHP: about empty()

The empty() helper is a built-in PHP function that is often used to check inputs.

The problem is it has some quirks you might not know yet.

What is it?

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.

source: PHP doc - empty

In code, it gives !isset($myVar) || $myVar == false;

We use that for anything and everything...

$testCase = array(
    1 => '',
    2 => "",
    3 => null,
    4 => array(),
    5 => FALSE,
    6 => NULL,
    7=>'0',
    8=>0,

);

foreach ($testCase as $k => $v) {
    if (empty($v)) {
        echo "<br> $k=>$v is empty";
    }
}
Enter fullscreen mode Exit fullscreen mode

source: PHP doc - empty

While this code is totally valid and makes sense for older versions of PHP, it might not be the best approach now that we have stricter types (e.g., PHP 8.*).

Besides, there are other functions for your specific case:

  • existence can be checked with if (isset($myVar))
  • null values can be tested with if ($myVar === null) or if (is_null($myVar)) (which is marginally faster)
  • empty array with if ($myArray === [])

Β―\(ツ)/Β― When empty() seems to "hallucinate"

<?php
class MyClass {
    private static $myProp = 123456;
}

$myObject = new MyClass();
print_r(empty($myObject::$myProp)); // 1
var_dump(empty($myObject::$myProp)); // true
Enter fullscreen mode Exit fullscreen mode

The property is just not accessible, but using empty() here would be confusing and prone to errors.

Another famous example is:

$myVar = '0';
var_dump(empty($myVar));// true
Enter fullscreen mode Exit fullscreen mode

When NOT to use

As empty($myVar) is !isset($myVar) || $myVar == false:

  • don't use it if you know that $myVar exists
  • don't use it to check boolean
  • don't use it for mixed types

N.B.: some would even say don't use it on latest versions of PHP, as you can now leverage built-in type safety

Β Wrap up

I'm not writing this to patronize or whatever, as I've been using Μ€empty()` for years in various projects, like many other developers, and for various checks.

It might be fine for now, but, with such generic helper, I'm afraid you will likely introduce technical debt in most cases, and harm readability.

Top comments (2)

Collapse
 
suckup_de profile image
Lars Moelleken

Hi, I also think, that writing more explicit what we mean is much easier too read in the end. And we spend more time reading code than writing it.

Collapse
 
spo0q profile image
spO0q πŸ’πŸŽƒ • Edited

we spend more time reading code than writing it.

Precisely!