Skip to content
Tutorials Center
My learning

Topics

PHP Reference ยท Language Constructs and Statements

PHP empty() language construct

Reference for PHP empty(): which values count as empty, how it differs from isset(), the "0" pitfall and why it never warns about missing variables.

empty() returns true when a variable does not exist or holds a value that PHP considers false. It is the opposite of isset($x) && $x, written in one word, and it never produces a warning for undefined variables, array keys or properties.

Because "empty" means "falsy", it also matches values you may want to keep, notably 0 and the string "0". That is the most common source of bugs with this construct.

PHP
if (empty($_POST['name'])) {
    echo "Please enter a name";
}

Try it

PHP Which values are empty

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

PHP Missing keys and the zero pitfall

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Syntax

PHP
empty(mixed $var): bool
Name Description
$var A variable, array element or property. Other expressions are allowed since PHP 5.5, for example empty(trim($s)).

Return value: true if the variable does not exist or its value converts to false; otherwise false.

Errors: none for undefined variables, keys or properties.

Usage notes

  • Empty values: null, false, 0, 0.0, "", "0", []. Everything else is not empty, including "0.0", " " and "false".
  • The "0" trap. An input field containing 0 is "empty". When zero is a valid answer, test with isset($x) && $x !== '' or compare to null.
  • empty($x) equals !isset($x) || !$x with no warnings. It does not distinguish "missing" from "falsy"; use isset() or array_key_exists() when that matters.
  • Objects are never empty, even if they have no properties. Check an object's contents yourself, for instance (array) $obj === [], or implement Countable.
  • Magic properties. For inaccessible properties, empty() calls __isset() first and only if it returns true calls __get() to read the value.
  • Use count() for arrays when you want a number, and $arr === [] for a strict emptiness check.
  • Strings of whitespace are not empty. Use trim($s) === '' to treat them as blank.
  • Readability. empty() is short, but explicit comparisons such as $list === [] or $s === '' say exactly what you mean and avoid surprises.