Check if value isset and null
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.
See Best way to test for a variable's existence in PHP; isset() is clearly broken
if( array_key_exists('foo', $GLOBALS) && is_null($foo)) // true & true => true
if( array_key_exists('bar', $GLOBALS) && is_null($bar)) // false & => false
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.
I found this topic when I was looking for a solution for an array. to check for the presence of an array element that contains NULL, this construction helped me
$arr= [];
$foo = 'foo';
$arr[$foo]= NULL;
if (array_key_exists('bar', $arr)) {}; // Should evaluate to FALSE
if (array_key_exists('foo', $arr)) {}; // Should evaluate to TRUE
if (array_key_exists($foo, $arr)) {}; // Should evaluate to TRUE