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.
if (empty($_POST['name'])) { echo "Please enter a name"; }
Try it
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.
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
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 containing0is "empty". When zero is a valid answer, test withisset($x) && $x !== ''or compare tonull. empty($x)equals!isset($x) || !$xwith no warnings. It does not distinguish "missing" from "falsy"; useisset()orarray_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 implementCountable. - Magic properties. For inaccessible properties,
empty()calls__isset()first and only if it returnstruecalls__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.
Related
isset,unset,bool, Loose comparison tables,count()- Lessons: Booleans and null, Type juggling