I need to check if value is defined as anything, including null. isset
treats null values as undefined and returns false
. Take the following as an
I have found that compact
is a function that ignores unset variables but does act on ones set to null
, so when you have a large local symbol table I would imagine you can get a more efficient solution over checking array_key_exists('foo', get_defined_vars())
by using array_key_exists('foo', compact('foo'))
:
$foo = null;
echo isset($foo) ? 'true' : 'false'; // false
echo array_key_exists('foo', compact('foo')) ? 'true' : 'false'; // true
echo isset($bar) ? 'true' : 'false'; // false
echo array_key_exists('bar', compact('bar')) ? 'true' : 'false'; // false
Update
As of PHP 7.3 compact() will give a notice for unset values, so unfortunately this alternative is no longer valid.
compact() now issues an E_NOTICE level error if a given string refers to an unset variable. Formerly, such strings have been silently skipped.
The following code written as PHP extension is equivalent to array_key_exists($name, get_defined_vars()) (thanks to Henrik and Hannes).
// get_defined_vars()
// https://github.com/php/php-src/blob/master/Zend/zend_builtin_functions.c#L1777
// array_key_exists
// https://github.com/php/php-src/blob/master/ext/standard/array.c#L4393
PHP_FUNCTION(is_defined_var)
{
char *name;
int name_len;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &name, &name_len) == FAILURE) {
return;
}
if (!EG(active_symbol_table)) {
zend_rebuild_symbol_table(TSRMLS_C);
}
if (zend_symtable_exists(EG(active_symbol_table), name, name_len + 1)) {
RETURN_TRUE;
}
}