This easy tutorial will show you how to use the PHP empty() function to check whether a variable can be considered empty and show some code examples.
What Is Empty?
A variable is considered empty in PHP if its value equates to FALSE or the variable does not exist.
This means that the following are considered empty:
- An empty string (“”)
- The number zero (0)
- In any form (0.0000)
- Including strings containing only a 0 character (“0”)
- Boolean FALSE
- NULL
- An undeclared variable
- Empty arrays
The empty() function is different from the isset() function. The latter checks only whether a variable is declared and not null.
PHP empty() Function Syntax
The syntax for the empty() function is as follows:
empty(VAR)
Note that:
- VAR should be the variable to be checked for emptiness
- empty() will return a boolean value (TRUE or FALSE)
- TRUE if the passed VAR is empty
- FALSE if it is not
- If the variable *VAR has not been declared, no error will be thrown!
- FALSE will be returned instead
Php empty() Function Examples
$var = NULL; if(empty($var)) echo $var . ' is empty!\n'; $var = '0'; if(empty($var)) echo $var . ' is empty!\n'; $var = 0; if(empty($var)) echo $var . ' is empty!\n'; $var = ''; if(empty($var)) echo $var . ' is empty!\n'; $var = ""; if(empty($var)) echo $var . ' is empty!\n'; $var = null; if(empty($var)) echo $var . ' is empty!\n'; $var = []; if(empty($var)) echo json_encode($var) . ' is empty!\n'; // The array is JSON encoded so it can be printed $var = (object)[]; // Creates an empty object if(empty($var)) echo json_encode($var) . ' is empty!\n'; // The object is JSON encoded so it can be printed $var = FALSE; if(empty($var)) echo $var . ' is empty!\n';
Notice that the empty object is not considered empty by isempty()!