PHP empty() Function
PHP empty() checks whether a variable is empty. It returns true when the variable does not exist, or when it has a “false-like” value such as 0, empty string or NULL.
It is mostly used in form validation, for example to find out if the user left a field blank.
Syntax
empty(mixed $var): bool
Parameters
| Parameter | Description |
|---|---|
| var | Required. The variable or expression you want to check |
Return value: true if the value is empty, otherwise false. empty() does not give any warning when the variable does not exist.
Which values are empty?
All the values in this table are considered empty by PHP.
| Value | empty() result |
|---|---|
| “” (empty string) | true |
| 0 (integer) | true |
| 0.0 (float) | true |
| “0” (string with zero) | true |
| NULL | true |
| false | true |
| [] (empty array) | true |
| Undefined variable | true |
| “0.0” (string) | false |
| ” ” (a single space) | false |
| “Hello” | false |
| [0] (array with one item) | false |
Examples
Example #1: Check simple values
<?php
$a = "";
$b = 0;
$c = "Hello";
var_dump(empty($a));
var_dump(empty($b));
var_dump(empty($c));
?>
Output:
bool(true)
bool(true)
bool(false)
Example #2: Undefined variable
The variable below is never created. empty() still works and gives true without any warning.
<?php
var_dump(empty($notDefined));
?>
Output:
bool(true)
Example #3: String “0” and arrays
<?php
var_dump(empty("0"));
var_dump(empty([]));
var_dump(empty([0]));
?>
Output:
bool(true)
bool(true)
bool(false)
Example #4: Form validation
A common use of empty() is to check if a required field is blank.
<?php
$username = "";
if (empty($username)) {
echo "Please enter your username.";
} else {
echo "Welcome, " . $username;
}
?>
Output:
Please enter your username.
isset() vs empty()
| Value | isset() | empty() |
|---|---|---|
| Undefined variable | false | true |
| NULL | false | true |
| “” (empty string) | true | true |
| 0 | true | true |
| “Hello” | true | false |
Common mistake: 0 is a valid value
Suppose a shop allows quantity 0. If you check it with empty(), PHP says it is empty and you show a wrong error message.
<?php
$quantity = 0;
// Wrong: 0 is a valid quantity but empty() returns true
if (empty($quantity)) {
echo "Please enter quantity.";
}
?>
Output:
Please enter quantity.
A better way is to check with isset() and compare with an empty string.
<?php
$quantity = 0;
if (!isset($quantity) || $quantity === "") {
echo "Please enter quantity.";
} else {
echo "Quantity is " . $quantity;
}
?>
Output:
Quantity is 0
Summary
- empty() returns true for “”, 0, “0”, NULL, false, [] and undefined variables.
- It never gives a warning for undefined variable.
- empty($x) is same as
!isset($x) || $x == false. - Do not use empty() when 0 or “0” is a valid value.
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |