How to Use empty() in PHP: Syntax, Examples, and Tips
In PHP,
empty() is a function used to check if a variable is empty or not set. It returns true if the variable has a value considered empty like 0, "", null, or false, and false otherwise. Use it to safely test variables without causing errors if they don't exist.Syntax
The empty() function checks if a variable is empty or not set. It takes one argument: the variable to check.
- Variable: The variable you want to test.
- Returns:
trueif the variable is empty or not set,falseotherwise.
php
empty($variable);
Example
This example shows how empty() returns true for different empty values and false for non-empty values.
php
<?php $values = ["", 0, 0.0, "0", null, false, [], "hello", 123]; foreach ($values as $value) { if (empty($value)) { echo "Empty\n"; } else { echo "Not Empty\n"; } } ?>
Output
Empty
Empty
Empty
Empty
Empty
Empty
Empty
Not Empty
Not Empty
Common Pitfalls
One common mistake is expecting empty() to only check for null or "". It treats 0, "0", false, and empty arrays as empty too. Also, empty() does not raise an error if the variable is not defined, unlike direct checks.
Wrong way (causes warning if variable not set):
if ($var == false) { /* ... */ }Right way (safe even if variable not set):
if (empty($var)) { /* ... */ }Quick Reference
empty() returns true for these values:
""(empty string)0(integer zero)0.0(float zero)"0"(string zero)nullfalse[](empty array)- Undefined variables
Key Takeaways
Use
empty() to check if a variable is empty or not set without errors.empty() treats 0, "0", false, null, "", and empty arrays as empty.It is safer than direct comparisons because it does not warn on undefined variables.
Remember
empty() returns a boolean: true if empty, false if not.Use
empty() to simplify checks before using variables in your code.