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 for which we will get True as return value from empty() function after checking.
0
0.0
"0"
""
NULL
FALSE
array()
Examples
<?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';
}
?>