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:
trueif the variable exists and is notNULLfalseotherwise
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 returntrueonly if all are set and notNULL. isset()returnsfalseif a variable is explicitly set toNULL.isset()works with arrays, objects, and normal variables.- Using
isset()helps avoidNotice: Undefined variableerrors in PHP.
Your Feedback
Help us improve by sharing your thoughts
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Terms Disclaimer About Us Contact Us
Copyright 2023-2025 © All rights reserved.
