The isset() function in php allows us to check if one or more variables have been declared to and is not null.

$variable = "I'm a variable";

if (isset($variable)) {
    echo "variable has been declared!";
} else {
   echo "variable hasn't been declared!"
}

if (isset($variable, $another_variable)) {
    echo "all variables have been declared!";
} else {
   echo "all variables haven't been declared!"
}

//Output:
variable has been declared!
all variables haven't been declared!

When working with variables in our php programs, it is useful to be able to check if a variable has been declared or not. In php, the isset() method is used for checking if variables have been defined or not.

We can check for the existence of a variable with the php isset() function.

The isset() function in php takes one or more variables and checks to see if the variable is declared and is different than null.

isset() returns true if the variable exists and false if the variable hasn’t been declared or is null.

If multiple variables are provided, isset() returns true only when all variables passed have been declared.

Below are some examples of using isset() in php to check if one or more variables have been declared.

$variable = "I'm a variable";

if (isset($variable)) {
    echo "variable has been declared!";
} else {
   echo "variable hasn't been declared!"
}

if (isset($variable, $another_variable)) {
    echo "all variables have been declared!";
} else {
   echo "all variables haven't been declared!"
}

$another_variable = "Another variable";

if (isset($variable, $another_variable)) {
    echo "all variables have been declared!";
} else {
   echo "all variables haven't been declared!"
}

//Output:
variable has been declared!
all variables haven't been declared!
all variables have been declared!

How to Check if a Function Exists in php with function_exists()

Another useful function in php is the function_exists() function, which allows you to check the existence of a given function.

We can use function_exists() in a similar way to isset() to check if a function exists.

If the function exists, function_exists return true. Otherwise, function_exists returns false.

Below are some examples of testing to see if a function exists in php.

if (function_exists('max')) {
    echo "max() exists!";
} else {
   echo "max() doesn't exist!";
}

if (function_exists('other_function')) {
    echo "other_function() exists!";
} else {
   echo "other_function() doesn't exist!";
}

//Output:
max() exists!
other_function() doesn't exist!

Hopefully this article has been useful for you to learn about isset() in php and how to use the isset() function.

Categorized in:

PHP,

Last Update: February 26, 2024