0
0
PhpHow-ToBeginner · 3 min read

How to Use isset in PHP: Syntax and Examples

In PHP, isset is used to check if a variable is set and is not null. It returns true if the variable exists and has a value other than null, otherwise it returns false. You can use it to avoid errors when accessing variables that may not be defined.
📐

Syntax

The isset function checks if a variable or multiple variables are set and not null. It returns true if all variables exist and are not null, otherwise false.

  • variable: The variable to check.
  • You can check multiple variables by separating them with commas.
php
isset(mixed $var, mixed ...$vars): bool
💻

Example

This example shows how to use isset to check if a variable is set before using it to avoid errors.

php
<?php
$name = "Alice";
if (isset($name)) {
    echo "Name is set: $name";
} else {
    echo "Name is not set.";
}

// Checking multiple variables
$age = 25;
if (isset($name, $age)) {
    echo "\nBoth name and age are set.";
} else {
    echo "\nOne or both variables are not set.";
}

// Variable not set example
if (isset($address)) {
    echo "\nAddress is set.";
} else {
    echo "\nAddress is not set.";
}
?>
Output
Name is set: Alice Both name and age are set. Address is not set.
⚠️

Common Pitfalls

Common mistakes when using isset include:

  • Expecting isset to check if a variable is empty or has a value like zero or an empty string. It only checks if the variable exists and is not null.
  • Using isset on array keys that do not exist returns false, which can be confusing.
  • Using isset on variables that are set to null returns false.

Example of wrong and right usage:

php
<?php
// Wrong: expecting isset to check if variable is empty
$var = "";
if (isset($var)) {
    echo "Variable is set."; // This will print even if $var is empty string
}

// Right: check if variable is not empty
if (!empty($var)) {
    echo "Variable is not empty.";
} else {
    echo "Variable is empty.";
}
?>
Output
Variable is set.Variable is empty.
📊

Quick Reference

  • Returns true if variable exists and is not null.
  • Returns false if variable does not exist or is null.
  • Can check multiple variables at once.
  • Does not check if variable is empty or zero.

Key Takeaways

Use isset to check if a variable exists and is not null before using it.
isset returns false for variables set to null or not defined.
It can check multiple variables at once, returning true only if all are set.
isset does not check if a variable is empty or zero, only if it exists.
Use empty if you want to check for empty values instead of just existence.