PHP isset()

Sunday, September 20th, 2009

The PHP function isset() is often used to determine the presence of a variable. When the variable is not defined, false is returned. Using isset() is also an easy way to determine whether an array has a given key.

$assoc = array('key' => 'value');
echo isset($assoc['key']) ? 'true' : 'false';
// true
echo isset($assoc['missing']) ? 'true' : 'false';
// false

There is a catch: isset() called on a null variable will return false.

$var = null;
echo isset($var) ? 'true' : 'false';
// false
 
$array = array('key' => null);
echo isset($array['key']) ? 'true' : 'false';
// false

For checking the presence of a key in an array, use the PHP function array_key_exists() instead.

echo array_key_exists('key', $array) ? 'true' : 'false';
// true
 
function has_empty($key, &$array) {
    return array_key_exists($key, $array) && !$array[$key];
}
echo has_empty('key', $array) ? 'true' : 'false';
// true

To determine the presence of a null variable, a custom function is required.

function isvar($var) {
    return isset($var) || @is_null($var);
}
$null = null;
echo isvar($null) ? 'true' : 'false';
// true

Leave a Reply