Follow
Follow

How to check whether a variable is empty in PHP

Empty() function

The empty() function is an built-in function in PHP which is used to check whether a variable is empty or not. A variable is empty if it does not exist or if its value equals false.

Note:

The empty() function does not create a warning if the variable does not exist which means empty() is equivalent to !isset($var) || $var == false.

List of empty Value :

  • 0 – 0 as an integer
  • “0” – 0 as a string
  • “” – An empty string
  • 0.0 – 0 as a float
  • NULL
  • FALSE
  • array() – An empty array
  • $var_name; – A variable declared but without a value in a class

Example:

<?php
$var1 = 0;
$var2 = NULL; 
$var3 = FALSE;
$var4 = 'PHP Tutorials';
$var5 = array();
$var6 = '';
 
// Testing the variables
if(empty($var1)){
    echo '$var1 is empty.';  //Output: $var1 is empty.
}
echo "<br>";
 
if(empty($var2)){
    echo '$var2 is empty.';  //Output: $var2 is empty.
}
echo "<br>";
 
if(empty($var3)){
    echo '$var3 is empty.';  //Output: $var3 is empty.
}
echo "<br>";
 
if(empty($var4)){
    echo '$var4 is empty.';  
}
else
{
    echo '$var 4 is not empty'; //Output: $var4 is not empty.
}
echo "<br>";
 
if(empty($var5)){
    echo '$var5 is empty.';  //Output: $var5 is empty.
}
echo "<br>";
if(empty($var6)){
    echo '$var6 is empty.';  //Output: $var6 is empty.
}
?>
Newsletter
Join Design Community
Get the latest updates, creative tips, and exclusive resources straight to your inbox. Let’s explore the future of design and innovation together.