It’s Festive Season! Enjoy 30% Off

Use code FESTIVE30 at checkout

Code has been added to clipboard!

Using PHP isset to Easily Check the Value of Variables

Reading time 2 min
Published Aug 5, 2019
Updated Sep 30, 2019

When you’re coding in PHP, your code holds multiple variables more often than not. It’s not that hard to get lost among them either. To make PHP check if a variable exists, you can use PHP isset(). Its name is rather self-explanatory: by using isset in PHP, you check whether a particular variable in the script is set or not.

PHP isset: Main Tips

  • By using isset in PHP, you can check whether a particular variable is set.
  • It returns a boolean value, True meaning a variable is set.
  • Just as echo and print, isset in PHP is a language construct and not a function.
  • To unset a particular variable in PHP, use the unset() function.

How to Use and Write isset() Correctly

PHP isset() determines whether a particular variable is set:

Example
$x = 'SpaceDoggo';
var_dump(isset($x));

It returns a boolean value, which is only True if all three conditions below are satisfied:

  • The variable is declared (has a value assigned).
  • This value is not Null.
  • The variable hasn't been unset using the unset() function.

The syntax for making PHP check if a variable exists with isset() is simple:

Example
isset($x)

You can use PHP isset() to check one or multiple variables, thus saving time:

Example
isset($x, $y, $z)

Note: if you check more than one variable, PHP isset will only return True if all of them are set.

Checking Variables in PHP: isset vs empty

To check the value of a certain PHP variable, you can also use PHP empty(). However, you should understand how different it is to isset():

Example
$x = 'EarthKitten';

var_dump(isset($x));
var_dump(empty($x));

The purpose of isset() and empty() seem alike and they both return boolean values. However, as you can see in the example, they return opposite values:

  • isset() returns True for set variables.
  • empty() returns True for unset or empty ones.

Note: one more difference is that empty() can take expressions as arguments, while isset() cannot.

PHP isset: Summary

  • To check if a certain variable is set, you can use PHP isset().
  • It is not actually a function, but a language construct, similarly as echo and print.
  • If checked variable is set, it returns a boolean value of True.
  • Variables can be unset with an unset() function.