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

chazomaticus picture chazomaticus · Jan 6, 2009 · Viewed 142.9k times · Source

From the isset() docs:

isset() will return FALSE if testing a variable that has been set to NULL.

Basically, isset() doesn't check for whether the variable is set at all, but whether it's set to anything but NULL.

Given that, what's the best way to actually check for the existence of a variable? I tried something like:

if(isset($v) || @is_null($v))

(the @ is necessary to avoid the warning when $v is not set) but is_null() has a similar problem to isset(): it returns TRUE on unset variables! It also appears that:

@($v === NULL)

works exactly like @is_null($v), so that's out, too.

How are we supposed to reliably check for the existence of a variable in PHP?


Edit: there is clearly a difference in PHP between variables that are not set, and variables that are set to NULL:

<?php
$a = array('b' => NULL);
var_dump($a);

PHP shows that $a['b'] exists, and has a NULL value. If you add:

var_dump(isset($a['b']));
var_dump(isset($a['c']));

you can see the ambiguity I'm talking about with the isset() function. Here's the output of all three of these var_dump()s:

array(1) {
  ["b"]=>
  NULL
}
bool(false)
bool(false)

Further edit: two things.

One, a use case. An array being turned into the data of an SQL UPDATE statement, where the array's keys are the table's columns, and the array's values are the values to be applied to each column. Any of the table's columns can hold a NULL value, signified by passing a NULL value in the array. You need a way to differentiate between an array key not existing, and an array's value being set to NULL; that's the difference between not updating the column's value and updating the column's value to NULL.

Second, Zoredache's answer, array_key_exists() works correctly, for my above use case and for any global variables:

<?php
$a = NULL;
var_dump(array_key_exists('a', $GLOBALS));
var_dump(array_key_exists('b', $GLOBALS));

outputs:

bool(true)
bool(false)

Since that properly handles just about everywhere I can see there being any ambiguity between variables that don't exist and variables that are set to NULL, I'm calling array_key_exists() the official easiest way in PHP to truly check for the existence of a variable.

(Only other case I can think of is for class properties, for which there's property_exists(), which, according to its docs, works similarly to array_key_exists() in that it properly distinguishes between not being set and being set to NULL.)

Answer

Zoredache picture Zoredache · Jan 6, 2009

If the variable you are checking would be in the global scope you could do:

array_key_exists('v', $GLOBALS)