The isset() function is used to check whether a variable is set or not. If the variable is already unset with the unset() function, it will no longer be set.
PHP isset
PHP isset() is a built-in function that checks whether a variable is set and is not NULL. The isset() function returns false if the testing variable contains a NULL. It accepts only variable references as arguments and not direct values.
The isset() function returns TRUE if a given variable is set to any value, including the empty string.
Syntax
See the following syntax.
bool isset($var, mixed)
Parameters
The first parameter of this function is $var. This parameter is used to store the value of the variable. The mixed indicates that a parameter may accept multiple.
Example
Let’s take a string variable example.
<?php $stranger = 'Eleven'; var_dump(isset($stranger));
See the output.
➜ pro php app.php bool(true) ➜ pro
Now, check the empty string.
<?php $stranger = ''; var_dump(isset($stranger));
See the output.
➜ pro php app.php bool(true) ➜ pro
Let’s check the NULL value.
<?php $stranger = NULL; var_dump(isset($stranger));
See the output.
➜ pro php app.php bool(false) ➜ pro
Let’s check the direct values and not the variables.
<?php var_dump(isset('Eleven'));
See the following output.
➜ pro php app.php PHP Fatal error: Cannot use isset() on the result of an expression (you can use "null !== expression" instead) in /Users/krunal/Desktop/code/php/pro/app.php on line 3 Fatal error: Cannot use isset() on the result of an expression (you can use "null !== expression" instead) in /Users/krunal/Desktop/code/php/pro/app.php on line 3 ➜ pro
So, I cannot use isset() on the result of an expression.
isset $_POST
Let’s say I have the form on one page that submits data to another. There, it checks if an input mail field is filled. If filled, do something; if it is not filled, do other things.
In the above scenario, we can check whether the variable is set. Based on that, we can put the server-side validation.
See the following code to implement the above scenario.
if (isset($_POST["mail"]) && !empty($_POST["mail"])) { echo "Yes, mail is set"; } else { echo "N0, mail is not set"; }
isset() function with multiple parameters
Let’s check more than one variable inside the isset() function.
<?php $mage = 'Eleven'; $villian = 'Mind Flayer'; var_dump(isset($mage, $villian));
See the following output.
➜ pro php app.php bool(true) ➜ pro
The empty() is the opposite of (boolean) var, except that no warning is generated when the variable is not set. See the following code.
if (!empty($_POST["mail"])) { echo "Yes, mail is set"; } else { echo "N0, mail is not set"; }
That’s it for this tutorial.