Before using variable we can check the value by using empty function in PHP. The advantage of using empty function is it will not generate any error message if the variable does not exist. This function empty() will return True or False ( Boolean return ) based on status of the variable.
if(empty($my_var)){echo " Variable is empty ";}
else {echo " Variable is not empty ";}
The output of above command is here
Variable is empty
Note that there is no warning message. We will get True as return value from empty() if it is null data or 0 etc.
Here is a list of values for which empty() will return True.
Here is a list for which we will get True as return value from empty() function after checking.
0
0.0
"0"
""
NULL
FALSE
array()
Examples
All statements below will return True for different values of variable $my_var
<?Php
$my_var="";
if(empty($my_var)){echo " True Variable is empty, <br>";}
else {echo " False "; }
$my_var="0";
if(empty($my_var)){echo " True Variable is empty, <br>";}
else {echo " False "; }
$my_var=0;
if(empty($my_var)){echo " True Variable is empty,<br> ";}
else {echo " False "; }
$my_var=0.0;
if(empty($my_var)){echo " True Variable is empty, <br>";}
else {echo " False "; }
$my_var=Null;
if(empty($my_var)){echo " True Variable is empty, <br>";}
else {echo " False "; }
$my_var=False;
if(empty($my_var)){echo " True Variable is empty,<br> ";}
else {echo " False "; }
$my_var=array();
if(empty($my_var)){echo " True Variable is empty, <br>";}
else {echo " False "; }
?>
Example 2
<?php
$my_var="";
echo empty($my_var);
?>
Output is
1
Difference between isset() and empty()
Include the commented line and check the difference.
<?php
$my_var = array();
// $my_var['some key']="Welcome "; // Include this line and check.
if (empty($my_var['some key'])) {
echo 'The value is either 0, empty, or not set at all<br>';
}else{
echo 'This is not empty, value is '. $my_var['some key']. '<br>';
}
if (isset($my_var['some key'])) {
echo 'True : Value is set';
}else{
echo 'This is False';
}
?>
←Declaring variables Cookies to store Infomation →
Getting Type of Variable→ var_dump()→ isset()→
← Subscribe to our YouTube Channel here