How to use isset and unset in PHP

While programming in PHP sometimes we will need to check if a variable exists and occasionally we may need to remove a variable. PHP provides two functions for completing these tasks; isset and unset.

 

In this tutorial, we will learn how to check if a variable exists and remove it if necessary using isset and unset in PHP.

 

isset() function

isset is used to check whether a variable has been defined in a PHP program. To use it, pass the name of the variable inside the () (parenthesis) of isset(). isset returns 1 or nothing so it can be used with if logic or the result can be stored in a variable.

 

$foo = 'hello';
$is_defined = isset($foo);
print_r($is_defined);
1

 

isset can be used to check if anything exists. A common use of isset is to check if an array index is defined:

 

$foo = [1, 2, 3];

if (isset($foo['5'])) {
  print_r('true');
} else {
  print_r('false');
}
false

 

unset() function

unset is used to completely remove a variable in PHP. Pass the name of the variable inside the () (parenthesis) of unset() to remove it.

 

$foo = [1, 2, 3];

unset($foo);

if (isset($foo)) {
  print_r('true');
} else {
  print_r('false');
}
false

 

To remove multiple variables, pass them as a , (comma) separated list inside unset().

 

$foo = [1, 2, 3];
$bar = [1, 2, 3];

unset($foo, $bar);

if (isset($foo) || isset($bar)) {
  print_r('true');
} else {
  print_r('false');
}
false

 

Conclusion

You know how to use isset in PHP to validate a variable exists and how to remove one or multiple variables using unset.

variable