Reliable Variable Existence Checking in PHP
The isset() function, while commonly used to verify variable existence, has a limitation: it considers variables set to NULL as existing. This raises the question of how to reliably determine a variable's presence in PHP.
One approach is to combine isset() with is_null():
<code class="php">if (isset($v) || @is_null($v))</code>
However, this method remains problematic due to is_null()'s behavior with unset variables.
Another option is to use the @($v === NULL) comparison. However, this also behaves like is_null().
For a more reliable approach, consider using array_key_exists(). This function operates correctly for both global variables and arrays:
<code class="php">$a = NULL; var_dump(array_key_exists('a', $GLOBALS)); // true var_dump(array_key_exists('b', $GLOBALS)); // false</code>
The above is the detailed content of How to Reliably Check for Variable Existence in PHP?. For more information, please follow other related articles on the PHP Chinese website!