PHP isset() function

PHP isset is used to check whether the variable is set or not.The PHP isset() function returns false if variable contains a NULL value. Syntax:

isset(variable1, variable2….)
Presentation of PHP isset: Presentation of PHP isset
  • In the above diagram, the isset variable is null so it will return false.
Isset Variable
  • In the above diagram, the isset variable is 10, and it will return true. It means if the variable is set and not null, then the isset() function will return true.
Example (Null Variable):
<?php
$var=null;
if(isset($var))
{
echo "True";
}
else{
echo "False";
}
?>
Output:
False
  • In the above example, the variable is null, and it will return the false result.
Example (Not NullVariable):
<?php
$var=2;
if(isset($var))
{
echo "True";
}
else{
echo "False";
}
?>
Output:
True
  • In the above example, the variable has 2 value, and it will return true
Example:
<!DOCTYPE html>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
//define variables and set to empty values
$genderEr = "";
$gender = "";
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST["gender"]))
   {
    $genderEr = "Gender is required";
  }
else
   {
    $gender = test_input($_POST["gender"]);
  }
}
functiontest_input($data)
{
$data = trim($data);
$data = stripslashes($data);
return $data;
}
?>
<form method="post" action="<?php ($_SERVER["PHP_SELF"]);?>">
 Gender:
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="female");?> value="female">Female
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="male") ;?> value="male">Male
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="trans");?> value="trans">TransGender
<span class="error">* <?php echo $genderEr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>

  • In the above example, the PHP isset() function is to check the variable ($gender) is set or not with a value( “female, male and trans”). 

PHP isset Examples

Example 1


Output

10 is set with isset function

Example 2


Output

Specified array is not set.

Example 3


Output

bool(true)
bool(true)

Example 4


Output

bool(false)
bool(true)

isset vs. empty vs. is_null :

  • isset() is to check if a variable is set with a value.
  • empty() is to check if a given variable is empty.
  • is_null() – It is to check whether a variable is defined as NULL.
Functions “” Null False Undefined 0
isset() True False True False True
empty() True True True True True
is_null() False True False Error False