Determine whether a variable is considered to be empty. A variable is considered empty if it does not exist or if its value equals FALSE
. empty() does not generate a warning if the variable does not exist.
Variable to be checked
Note:
Prior to PHP 5.5, empty() only supports variables; anything else will result in a parse error. In other words, the following will not work: empty(trim($name)). Instead, use trim($name) == false.
No warning is generated if the variable does not exist. That means empty() is essentially the concise equivalent to !isset($var) || $var == false.
Returns FALSE
if var
exists and has a non-empty, non-zero value. Otherwise returns TRUE
.
The following things are considered to be empty:
- "" (an empty string)
- 0 (0 as an integer)
- 0.0 (0 as a float)
- "0" (0 as a string)
NULL
FALSE
- array() (an empty array)
- $var; (a variable declared, but without a value)
empty() now supports expressions, rather than only variables.
Checking non-numeric offsets of strings returns TRUE
.
When using empty() on inaccessible object properties, the __isset() overloading method will be called, if declared.
1 2 3 4 5 6 7 8 9 10 11 12 13 | <?php $var = 0; // Evaluates to true because $var is empty if ( empty ( $var )) { echo '$var is either 0, empty, or not set at all' ; } // Evaluates as true because $var is set if (isset( $var )) { echo '$var is set even though it is empty' ; } ?> |
PHP 5.4 changes how empty() behaves when passed string offsets.
1 2 3 4 5 6 7 8 9 | <?php $expected_array_got_string = 'somestring' ; var_dump( empty ( $expected_array_got_string [ 'some_key' ])); var_dump( empty ( $expected_array_got_string [0])); var_dump( empty ( $expected_array_got_string [ '0' ])); var_dump( empty ( $expected_array_got_string [0.5])); var_dump( empty ( $expected_array_got_string [ '0.5' ])); var_dump( empty ( $expected_array_got_string [ '0 Mostel' ])); ?> |
Output of the above example in PHP 5.3:
bool(false) bool(false) bool(false) bool(false) bool(false) bool(false)
Output of the above example in PHP 5.4:
bool(true) bool(false) bool(false) bool(false) bool(true) bool(true)
isset() -
unset() -
count() -
strlen() -
Please login to continue.