PHP empty() Function
The PHP empty() function checks whether a variable is considered to be empty. A variable is considered empty if it does not exist or if its value equals false. The following value will evaluates to false:
- 0
- 0.0
- "0"
- ""
- NULL
- FALSE
- array()
The function returns true if the variable is considered to be empty, otherwise it returns false. Please note that this function does not generate any warning if the variable does not exist.
Syntax
empty(variable)
Parameters
variable |
Required. Specify the variable being evaluated. |
Return Value
Returns true if variable is considered to be empty, false otherwise.
Example:
The example below shows the usage of empty() function.
<?php var_dump(empty(NULL)); //returns: bool(true) var_dump(empty($xyz)); //returns: bool(true) var_dump(empty(0)); //returns: bool(true) var_dump(empty('0')); //returns: bool(true) var_dump(empty(false)); //returns: bool(true) var_dump(empty('')); //returns: bool(true) var_dump(empty(array())); //returns: bool(true) echo "\n"; var_dump(empty(10)); //returns: bool(false) var_dump(empty('xyz')); //returns: bool(false) var_dump(empty(true)); //returns: bool(false) var_dump(empty(array(10, 20))); //returns: bool(false) ?>
The output of the above code will be:
bool(true) bool(true) bool(true) bool(true) bool(true) bool(true) bool(true) bool(false) bool(false) bool(false) bool(false)
Example:
Consider the example below where this function is used to check all elements of an array if they are considered to be empty or not.
<?php $Arr = array($x, 10, null, false, true, '0', 0, "xyz", 0, array()); foreach ($Arr as $value) { echo "empty(".var_export($value, true).") = "; var_dump(empty($value)); } ?>
The output of the above code will be:
empty(NULL) = bool(true) empty(10) = bool(false) empty(NULL) = bool(true) empty(false) = bool(true) empty(true) = bool(false) empty('0') = bool(true) empty(0) = bool(true) empty('xyz') = bool(false) empty(0) = bool(true) empty(array ( )) = bool(true) PHP Warning: Undefined variable $x in Main.php on line 2
Example:
Consider one more example which illustrates on finding a variable which is empty but set.
<?php $x = 0; //returns true as $x is empty if (empty($x)) { echo "Variable 'x' is empty.\n"; } //returns true as $x is set if (isset($x)) { echo "Variable 'x' is set."; } ?>
The output of the above code will be:
Variable 'x' is empty. Variable 'x' is set.
❮ PHP Variable Handling Reference