To check whether a variable is empty in PHP, you can use the empty()
function. This function returns true
if the variable is empty, and false
otherwise.
A variable is considered empty if it is:
null
- an empty string (
''
) - a string of whitespaces (
' '
) - an empty array (
array()
) - a number that is equal to 0 (
0
,0.0
,0e0
) - a boolean that is equal to
false
For example:
$var = '';
if (empty($var)) {
echo '$var is empty';
} else {
echo '$var is not empty';
}
This would output $var is empty
.
You can also use the isset()
function to check whether a variable is set and is not null
. This function returns true
if the variable is set and is not null
, and false
otherwise.
For example:
$var = '';
if (isset($var)) {
echo '$var is set';
} else {
echo '$var is not set';
}
This would output $var is set
.