PHP: empty() function


The empty() function is used to check whether a variable is empty or not. Often, you may encounter a scenario, when you need to code in fashion if a variable is empty or another thing if it is not so. In these situations, empty function comes to rescue.


(PHP 4 and above)




Name Description Required /
var_name The variable being checked. Required Mixed*

*Mixed : Mixed indicates that a parameter may accept multiple (but not necessarily all) types.

Return value:

FALSE if var_name has a non-empty and non-zero value.

Value Type: Boolean

List of empty things :

  • "0" (0 as a string)
  • 0 (0 as an integer)
  • "" (an empty string)
  • NULL
  • "" (an empty string)
  • array() (an empty array)
  • $var_name; (a variable declared but without a value in a class)

Example :

$istr1='Learning empty';
if (empty($ivar1))
echo '$ivar1'." is empty or 0. <br />";
echo '$ivar1'." is not empty or 0. <br />";
if (empty($istr1))
echo '$istr1'." is empty or 0. <br />";
echo '$istr1' ." string is not empty or 0. <br />";


$ivar1 is empty or 0.
$istr1 string is not empty or 0. 

View the example in the browser

Practice here online :

See also

PHP Function Reference

Previous: debug_zval_dump
Next: floatval

PHP: Tips of the Day

SQL injection that gets around mysql_real_escape_string()

Consider the following query:

$iId = mysql_real_escape_string("1 OR 1=1");    
$sSql = "SELECT * FROM table WHERE id = $iId";

mysql_real_escape_string() will not protect you against this. The fact that you use single quotes (' ') around your variables inside your query is what protects you against this. The following is also an option:

$iId = (int)"1 OR 1=1";
$sSql = "SELECT * FROM table WHERE id = $iId";

Ref : https://bit.ly/32q3bJ7