Best way to test for a variable's existence in PHP; isset() is clearly broken

In PHP, the isset() function is used to check if a variable has been set, meaning that it has been declared and is not equal to NULL. However, it does have some limitations, such as not being able to detect if a variable has been set to NULL or if a variable is set within an object or an array.

Watch a course Learn object oriented PHP

Another way to check for the existence of a variable in PHP is to use the empty() function. This function returns TRUE if a variable is empty, which includes variables that have been set to NULL, an empty string, or the number 0.

You could also use the !== operator, it returns true if the variable is set and is not null, otherwise false.


$variable = "some value";

if ($variable !== null) {
  echo "The variable is set to: " . $variable;
} else {
  echo "The variable is not set";

Finally, It's also possible to check if a variable is defined in the global namespace using the defined() function.


define('VARIABLE_NAME', 'some value');

if (defined('VARIABLE_NAME')) {
  echo "The constant is defined";
} else {
  echo "The constant is not defined";

In conclusion, the best way to check for the existence of a variable depends on the specific use case and what you are trying to accomplish. Each function and operator has its own specific use case, so it's important to understand the differences and choose the one that fits your needs best.