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 example:
$foo = null;
if(isset($foo)) // returns false
if(isset($bar)) // returns false
if(isset($foo) || is_null($foo)) // returns true
if(isset($bar) || is_null($bar)) // returns true, raises a notice
Note that $bar
is undefined.
I need to find a condition that satisfies the following:
if(something($bar)) // returns false;
if(something($foo)) // returns true;
Any ideas?
You could use is_null and empty instead of isset(). Empty doesn't print an error message if the variable doesn't exist.
Here some silly workaround using xdebug. ;-)
If you are dealing with object properties whcih might have a value of NULL you can use:
property_exists()
instead ofisset()
See Best way to test for a variable's existence in PHP; isset() is clearly broken
is_null($bar)
returns true, since it has no values at all. Alternatively, you can use:to check if
$bar
is defined and will only return true if:I have found that
compact
is a function that ignores unset variables but does act on ones set tonull
, so when you have a large local symbol table I would imagine you can get a more efficient solution over checkingarray_key_exists('foo', get_defined_vars())
by usingarray_key_exists('foo', compact('foo'))
: