How to check whether a variable is empty in PHP

Topic: PHP / MySQL« Prev|Next »

Answer: Use the PHP empty() function

You can use the PHP empty() function to find out whether a variable is empty or not. A variable is considered empty if it does not exist or if its value equals FALSE.

  • <?php
  • $var1 = '';
  • $var2 = 0;
  • $var3 = NULL;
  • $var4 = FALSE;
  • $var5 = array();
  •  
  • // Testing the variables
  • if(empty($var1)){
  •     echo 'This line is printed, because the $var1 is empty.';
  • }
  • echo "<br>";
  •  
  • if(empty($var2)){
  •     echo 'This line is printed, because the $var2 is empty.';
  • }
  • echo "<br>";
  •  
  • if(empty($var3)){
  •     echo 'This line is printed, because the $var3 is empty.';
  • }
  • echo "<br>";
  •  
  • if(empty($var4)){
  •     echo 'This line is printed, because the $var4 is empty.';
  • }
  • echo "<br>";
  •  
  • if(empty($var5)){
  •     echo 'This line is printed, because the $var5 is empty.';
  • }
  • ?>
 

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


Related FAQ

Here are some more FAQ related to this topic:

 
Close

Your Feedback:

 

We would love to hear from you! Please say something.