In php, we can check if a variable exists with the php isset() function.

$variable = "I'm a variable";

if (isset($variable)) {
    echo "variable exists!";
} else {
   echo "variable doesn't exist!"
}

//Output:
variable exists!

When working with variables in our php programs, it is useful to be able to check if a variable exists or not.

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

If the variable exists, isset() return true. Otherwise, isset() returns false.

Below are some examples of using isset() in php to check if a variable exists.

$variable1 = "I'm a variable";

if (isset($variable1)) {
    echo "variable1 exists!";
} else {
   echo "variable1 doesn't exist!";
}

if (isset($variable2)) {
    echo "variable2 exists!";
} else {
   echo "variable2 doesn't exist!";
}

//Output:
variable1 exists!
variable2 doesn't exist!

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 how to check if a variable exists or not in php.

Categorized in:

PHP,

Last Update: February 26, 2024