In this tutorial we will learn How To Check if Variable is Empty in PHP. PHP empty() function is a built-in function which can be used to check whether a variable is empty or it has a value.
Table of Contents
PHP empty() Function
PHP empty() Function checks if a variable has a value or not.
In this example we will also use empty() function to check whether a variable is empty or it has a value.
<?php
$variable = "HowToCodeSchool.com";
if(empty($variable))
{
echo "Variable is Empty";
}
else
{
echo "Variable is Not Empty";
}
?>
In above code, else block will be executed since the variable is not empty.
<?php
$variable = "";
if(empty($variable))
{
echo "Variable is Empty";
}
else
{
echo "Variable is Not Empty";
}
?>
While in second example, variable is empty since it has no value.
Note: 0, "0", "", NULL, FALSE and array() are considered as empty values.
Equal Operator
We can also use simple equal operator to check if variable is empty or not.
<?php
$variable = "";
if($variable == '')
{
echo "Variable is Empty";
}
else
{
echo "Variable is Not Empty";
}
?>