The isset() function in PHP is a built-in tool used to check whether a variable, array element, session, or form field (like $_POST or $_GET) is set and not null. It returns true if the value exists and is not null; otherwise, it returns false.
This function is crucial for preventing “undefined variable” errors and for controlling logic based on input presence.
📘 Syntax of isset()
isset(mixed $var): bool
$varcan be any type: a string variable, array element, object property,$_POST,$_GET, etc.- Returns
trueif the variable is set and notnull. - Returns
falseif the variable is not set or explicitly set tonull.
✅ PHP isset() Function Example:
<?php
$my_name = 'Ateeq';
if (isset($my_name)) {
echo 'My name is ' . $my_name;
} else {
echo 'My name is not set.';
}
if (isset($my_email)) {
echo 'My email is set.';
} else {
echo 'My email is not set.';
}
?>
🖥️ Output:
My name is Ateeq
My email is not set.
Explanation:
$my_nameis defined and not null →isset()returnstrue.$my_emailis never defined →isset()returnsfalse.
🧠 Use Cases of isset() in PHP
- ✅ Validating form input (
$_POST['email']) - ✅ Checking session variables (
$_SESSION['user_id']) - ✅ Avoiding “undefined index” or “undefined variable” warnings
- ✅ Conditionally rendering data or logic
⚠️ isset() vs empty() vs array_key_exists()
| Function | Returns true if… | Returns false if… |
|---|---|---|
isset($var) | Variable is set and not null | Variable is not set or is null |
empty($var) | Variable is empty ('', 0, null, false) | Variable contains data |
array_key_exists() | Key exists in the array (even if value is null) | Key does not exist in array |
Use isset() when you’re checking if a variable exists and is not null.
📌 Final Thoughts
The isset() function is a vital part of writing secure and error-free PHP applications. Whether you’re validating form submissions, checking session variables, or managing user inputs, isset() ensures that you only work with variables that exist and contain data.
Pro Tip: Always combine isset() with !empty() if you want to ensure both existence and a meaningful value.
