What is empty() Function in PHP? (With Examples)
The empty() function in PHP is used to check whether a variable is considered empty. It is commonly used in PHP scripts to validate form fields, check variable values, and handle optional parameters.
If the variable is empty, empty() returns true; otherwise, it returns false.
Syntax of empty() Function
empty(mixed $var): bool
- $var: The variable you want to check.
 
- Return Value: Returns 
true if the variable is empty; otherwise, returns false. 
When is a Variable Considered Empty in PHP?
In PHP, a variable is considered empty if it:
- Does not exist.
 
- Is set to 
"" (an empty string). 
- Is set to 
0 (0 as an integer). 
- Is set to 
"0" (0 as a string). 
- Is set to 
NULL. 
- Is set to 
FALSE. 
- Is an empty array (
[]). 
- Is an empty object that implements 
Countable with count 0. 
Basic Example of empty() in PHP
<?php
$name = "";
if (empty($name)) {
    echo "The name field is empty.";
} else {
    echo "The name field is not empty.";
}
?>
Output:
The name field is empty.
In this example, $name is an empty string, so empty($name) returns true.
More Examples of empty() Usage
Example 1: Check If a Form Field is Filled
<?php
$email = $_POST['email'] ?? '';
if (empty($email)) {
    echo "Please enter your email address.";
} else {
    echo "Thank you for providing your email.";
}
?>
Example 2: Using empty() with Numbers
<?php
$quantity = 0;
if (empty($quantity)) {
    echo "Quantity is not set or is zero.";
} else {
    echo "Quantity is available.";
}
?>
Since $quantity is 0, which is considered empty, the output will be:
Quantity is not set or is zero.
Important Points About empty() in PHP
- No Warning for Undefined Variables: Unlike 
isset(), the empty() function does not throw a warning if the variable is not defined. 
- Comparison with 
isset():
isset() checks if a variable is set and not NULL. 
empty() checks if a variable is considered empty. 
 
Difference Between isset() and empty()
<?php
// Suppose $var is not set at all
var_dump(isset($var)); // Output: bool(false)
var_dump(empty($var)); // Output: bool(true)
?>