PHP empty() Function
The empty() function is used to check if a variable is empty.
empty() determines if a variable is considered empty. A variable is considered empty if it does not exist or if its value is equal to FALSE. If the variable does not exist, empty() does not generate a warning.
Starting from version 5.5, empty() supports expressions, not just variables.
Version Requirements: PHP 4, PHP 5, PHP 7
Syntax
bool empty ( mixed $var )
Parameter Description:
- $var: The variable to be checked.
Note: Before PHP 5.5, empty() only supported variables; anything else would cause a parse error. In other words, the following code would not work:
empty(trim($name))
As an alternative, you should use:
trim($name) == false
empty() does not generate a warning even if the variable does not exist. This means empty()
is essentially equivalent to !isset($var) || $var == false
.
Return Value
Returns FALSE if var exists and has a non-empty, non-zero value; otherwise, it returns TRUE.
The following variables are considered empty:
""
(empty string)0
(integer 0)0.0
(float 0)"0"
(string 0)NULL
FALSE
array()
(empty array)$var;
(a declared variable with no value)
Example
<?php
$ivar1 = 0;
$istr1 = 'tutorialpro';
if (empty($ivar1)) {
echo '$ivar1' . " is empty or 0." . PHP_EOL;
} else {
echo '$ivar1' . " is not empty or 0." . PHP_EOL;
}
if (empty($istr1)) {
echo '$istr1' . " is empty or 0." . PHP_EOL;
} else {
echo '$istr1' . " string is not empty or 0." . PHP_EOL;
}
?>
The execution result is as follows:
$ivar1 is empty or 0.
$istr1 string is not empty or 0.