Appearance
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 returns false for variables that exist but hold falsy values like 0, "", or false, which is why it is often considered unreliable for strict existence checks. It also works correctly for array elements and object properties.
Another approach is the empty() function. Note that empty() checks if a variable is "falsy" (e.g., NULL, empty string, 0, false, or an empty array) rather than strictly checking for existence. It will also trigger a warning if the variable is not defined.
You can also use the !== null operator to check if a variable holds a non-null value. However, this operator will trigger an "undefined variable" notice if the variable has not been declared. It is safest to use it only when you already know the variable exists, or combine it with isset().
Example of testing for a variable's existence in PHP
php
<?php
// $variable is not defined
if ($variable !== null) {
echo "The variable is set to: " . $variable;
} else {
echo "The variable is not set";
}For arrays and objects, use array_key_exists() and property_exists() respectively. Unlike isset(), these functions return true even if the key or property holds a null value, making them safer for strict existence checks.
| Method | Checks Existence? | Handles Falsy Values? | Warns on Undefined? |
|---|---|---|---|
isset() | Yes | No (returns false) | No |
empty() | No (checks falsy) | Yes | Yes |
!== null | No (checks value) | Yes | Yes |
array_key_exists() | Yes | Yes | No |
property_exists() | Yes | Yes | No |
Finally, note that the defined() function is used to check for constants, not variables. It cannot be used to test variable existence.
Example of using the defined() function for constants
php
<?php
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.