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?
Definition and Usage The isset() function determines whether a variable is set. To be considered a set, it should not be NULL. Thus, the isset() function also checks whether a declared variable, array or array key has a null value. It returns TRUE when the variable exists and is not NULL; else, it returns FALSE.
The isset() function is an inbuilt function in PHP which checks whether a variable is set and is not NULL. This function also checks if a declared variable, array or array key has null value, if it does, isset() returns false, it returns true in all other possible cases.
Determine if a variable is set and is not NULL . If a variable has been unset with unset(), it will no longer be set. isset() will return FALSE if testing a variable that has been set to NULL . Also note that a null character ("\0") is not equivalent to the PHP NULL constant.
PHP empty() Function The empty() function checks whether a variable is empty or not. This function returns false if the variable exists and is not empty, otherwise it returns true.
IIRC, you can use get_defined_vars()
for this:
$foo = NULL; $vars = get_defined_vars(); if (array_key_exists('bar', $vars)) {}; // Should evaluate to FALSE if (array_key_exists('foo', $vars)) {}; // Should evaluate to TRUE
If you are dealing with object properties which might have a value of NULL you can use: property_exists()
instead of isset()
<?php class myClass { public $mine; private $xpto; static protected $test; function test() { var_dump(property_exists($this, 'xpto')); //true } } var_dump(property_exists('myClass', 'mine')); //true var_dump(property_exists(new myClass, 'mine')); //true var_dump(property_exists('myClass', 'xpto')); //true, as of PHP 5.3.0 var_dump(property_exists('myClass', 'bar')); //false var_dump(property_exists('myClass', 'test')); //true, as of PHP 5.3.0 myClass::test(); ?>
As opposed with isset(), property_exists() returns TRUE even if the property has the value NULL.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With