empty() is convenient when a missing or false-like value should be treated as empty. Remember that values such as 0 and the string '0' are also considered empty, so use a stricter comparison when zero is meaningful.
<?php
$quantity = 0;
if ($quantity === 0) {
echo 'Quantity is zero';
}
?>
<?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 "; }
?>
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.
if(empty($my_var)){echo " Variable is empty ";}<br>
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. 0
0.0
"0"
""
NULL
FALSE
array()
<?php
$my_var="";
echo empty($my_var);
?>
Output is
1
<?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()
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.