Signup/Sign In

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.



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.