LAST UPDATED: AUGUST 4, 2021
How to check whether a variable is empty in PHP?
Answer: Using empty()
function
The empty()
function is a built-in function in PHP that is used to check whether the given string is empty or not. This function returns false when the variable exists and is not empty otherwise, it returns true.
Here are some values that evaluate to true when used with empty() function:
- 0
- 0.0
- "0"
- ""
- NULL
- false
- array()
Syntax
empty(variable);
Example
In the given example, we have created a variable named $var
and specified its value 'hello'. Then, we have checked whether the variable is empty or not using the empty()
function.
<!DOCTYPE html>
<html>
<head>
<title>empty() function</title>
</head>
<body>
<?php
$var1 = 'hello';
if(empty($var1)){
echo 'This line is printed, because the $var1 is empty.';
}
else{
echo "false";
}
?>
</body>
</html>
Output
false
Example 2
In the given example, we have specified the value of the $var()
function to NULL. Then, we have checked whether the $var
is empty or not using the empty()
function. This function returns true because any variable holding value null is considered as an empty variable.
<!DOCTYPE html>
<html>
<head>
<title>empty() function</title>
</head>
<body>
<?php
$var1 = NULL;
if(empty($var1)){
echo 'True';
}
else{
echo "False";
}
?>
</body>
</html>
Output
True
Conclusion
In this lesson, we have discussed how to check whether a variable is empty in PHP. We can find out whether a variable is empty or not using the empty()
function. This function returns true when the variable does not hold any value and returns false when the variable holds some value.