PUBLISHED ON: AUGUST 9, 2021
How to check whether a variable is null in PHP?
Answer: Using is_null()
function
We can check whether a variable is null or not using the is_null()
function. This function takes a variable as its input and returns true if the variable is null otherwise it returns false.
Example: Check whether a variable is null
In the given example, we have checked whether the variable is null or not using the is_null() function.
<!DOCTYPE html>
<html>
<head>
<title>Check whether a variable is null</title>
</head>
<body>
<?php
$var = NULL;
if(is_null($var)){
echo 'Variable is null';
}
?>
</body>
</html>
Variable is null
Apart from null values, the is_null() function also returns true for undefined variables.
Example: Check whether a undefined variable is null
In the given example, we checked whether the variable is null or not using the is_null()
function.
<!DOCTYPE html>
<html>
<head>
<title>Check whether a variable is null</title>
</head>
<body>
<?php
if(is_null($var)){
echo 'Variable is null';
}
?>
</body>
</html>
Variable is null
Conclusion
In this lesson, we have learned, how to check whether a variable is null not. So, here we have used the is_null()
function to check whether the variable is null or not.