What is isset() in PHP? (With Examples)
When working with PHP, one of the most important functions you'll frequently use is isset(). It helps you check whether a variable is set and is not null. Understanding how isset() works can help you write more secure and error-free code, especially when handling user inputs, arrays, or object properties.
In this article, we'll explain the isset() function in PHP, how it works, and show practical examples to make it easy for beginners and professionals.
What is isset() Function in PHP?
The isset() function in PHP checks if a variable is set and is not NULL. It returns:
true if the variable exists and is not NULL
false otherwise
Syntax:
isset(mixed $var, mixed ...$vars): bool
You can pass one or more variables into isset(), and it will only return true if all variables are set and not NULL.
Why Use isset() in PHP?
- To avoid errors when accessing undefined variables
- To validate user input in forms
- To check array keys before accessing them
- To optimize code by preventing unnecessary operations on null or undefined values
PHP isset() Function Examples
1. Basic Example of isset()
<?php
$name = "John";
if (isset($name)) {
echo "Name is set.";
} else {
echo "Name is not set.";
}
?>
Output:
Name is set.
Here, $name is set and not NULL, so isset($name) returns true.
2. Checking an Undefined Variable
<?php
if (isset($age)) {
echo "Age is set.";
} else {
echo "Age is not set.";
}
?>
Output:
Age is not set.
Since $age is not defined, isset($age) returns false.
3. Using isset() with Multiple Variables
<?php
$a = "Hello";
$b = "World";
if (isset($a, $b)) {
echo "Both variables are set.";
} else {
echo "One or both variables are not set.";
}
?>
Output:
Both variables are set.
isset() checks both $a and $b. It returns true only if both are set and not NULL.
4. isset() with Array Elements
<?php
$person = [
"name" => "Alice",
"age" => 25
];
if (isset($person['name'])) {
echo "Name exists: " . $person['name'];
}
?>
Output:
Name exists: Alice
Always check if an array key exists using isset() before accessing it to avoid warnings.
Important Points About isset()
- If you use
isset() on multiple variables, it will return true only if all are set and not NULL.
isset() returns false if a variable is explicitly set to NULL.
isset() works with arrays, objects, and normal variables.
- Using
isset() helps avoid Notice: Undefined variable errors in PHP.