Signup/Sign In

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.



About the author:
I am the founder of Studytonight. I like writing content about C/C++, DBMS, Java, Docker, general How-tos, Linux, PHP, Java, Go lang, Cloud, and Web development. I have 10 years of diverse experience in software development.