Through this tutorial, you will learn different techniques to check if a variable is empty in PHP.
How do you check if the variable is empty in PHP?
In PHP, there are several ways to check if a variable is empty:
- Using empty() Function
- Using isset() Function
- Using strlen() Function
- Using is_null()
Using empty() Function
The empty() function is a built-in PHP function that checks if a variable is considered empty. A variable is considered empty if it has no value, or if the value is NULL, 0, “”, false, array() or “0”.
Here’s an syntax of empty() function:
empty($variable);
In PHP empty funciton the given variables can be of different types like an integer, string or even an array etc.
Here’s an example of using the empty() function to check if a variable is empty:
$var = ''; if (empty($var)) { echo 'Variable is empty'; } else { echo 'Variable is not empty'; }
Using isset() Function
Another common method to check if a variable is empty is to use the isset() function. The isset() function is a built-in PHP function that checks if a variable is declared and is not NULL.
Here’s an example of using the isset() function to check if a variable is empty:
$var = '';
if (isset($var) && $var !== '') {
echo 'Variable is not empty';
} else {
echo 'Variable is empty';
}
Using strlen() Function
The strlen() function is another method to check if a variable is empty in PHP. The strlen() function is a built-in PHP function that returns the length of a string.
Here’s an example of using the strlen() function to check if a variable is empty:
$var = '';
if (strlen($var) == 0) {
echo 'Variable is empty';
} else {
echo 'Variable is not empty';
}
Using is_null()
The is_null() function is a built-in PHP function that checks if a variable is NULL. It returns true if the variable is NULL, and false otherwise.
Here’s an example of how to use the is_null() function:
$myVar = NULL;
if (is_null($myVar)) {
echo "The variable is empty";
} else {
echo "The variable is not empty";
}
Conclusion
In PHP, checking if a variable is empty is a common task that is required in many programming scenarios. There are different methods to check if a variable is empty, including using the empty() function, isset(), is_null() function, and strlen() function.