PHP Empty Function – Add is empty variable check in php

Throughout php empty() function tutorial, we are going to share how to use php empty function and why we use it. The empty function check is a given variable is empty or now.

Basically 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 empty() Function

The empty() function checks whether a variable is empty or not.

This function returns false if the variable exists and is not empty, otherwise it returns true.

The following values evaluates to empty:

  • 0
  • 0.0
  • “0”
  • “”
  • NULL
  • FALSE
  • array()

Syntax

empty(variable);

PHP empty function Example

Here we have added PHP empty() function example where we you check the all empty variables:

<?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.';
}
?>

Output:

This line is printed, because the $var1 is empty.
This line is printed, because the $var2 is empty.
This line is printed, because the $var3 is empty.
This line is printed, because the $var4 is empty.
This line is printed, because the $var5 is empty.

Check if array is empty in php

<?php
  $arr = array(); 
  if (empty($arr)) {
  	 echo 'this array is empty';
  } else {
  	 echo 'this array is not empty';
  }
   
?> 

Output:

this array is empty

Why we use the empty function?

Sometimes, you need to check if a variable contains a value or not before proceeding to some action.

For example, you are taking the input values from the user in a web form. A few fields like Name, email, address are mandatory in the form. While you can check it at the client side by using the JavaScript, however, sometimes it may be disabled.

In that case, you may check the variable values by using the empty function to ensure that a user has entered some values or otherwise redirect the user back to the form page rather than proceeding to save the information in the database.

Leave a Comment