Check if variable is_undefined in PHP
I haven´t used it yet - but I think that "get_defined_vars" should be worth a look... http://php.net/manual/en/function.get-defined-vars.php
I would give it a try and dump the result.
You can use compact()
for this too, if the variable you give it isn't in the symbol table it returns an empty array, otherwise an array containing the variable name/value pair, just cast the result to a boolean
<?php
$myNull = null;
$isDefined = (bool) compact('myNull'); // true
$otherIsDefined = (bool) compact('myUndefined'); // false
If you want an is_undefined function I would prefer not to work with arrays so I would do this:
function is_undefined(&$test) {
return isset($test) && !is_null($test);
}
So when you echo isset($myNull);
it converts the boolean(true) to "". thats why the value is blank. If you want to see it on the screen you can do var_dump(isset($myNull));
that will display if it's true or false.
Also you have an echo of $myUndefined but it's not set yet so that's why you get a warning. What you want to do is:
if (!empty($myUndefined)) {
// variable is defined so do something with it
echo '$myUndefined value = "' . $myUndefined . '"<br />';
} else {
echo 'Oops, $myUndefined is Undefined!<br />";
}
Here is a brief overview of isset() vs. is_null() vs. empty()
$foo = null;
// isset($foo) == true;
// empty($foo) == true;
// is_null($foo) == true;
// Notice I don't set $foo2 to anything
// isset($foo2) == false;
// empty($foo2) == true;
// is_null($foo2) throws a notice!
$foo3 = false;
// isset($foo2) == true;
// empty($foo2) == true;
// is_null($foo2) == false;
$foo4 = 1234;
// isset($foo2) == true;
// empty($foo2) == false;
// is_null($foo2) == false;
I think that get_defined_vars is a good candidate for such job:
array_key_exists('myNull', get_defined_vars());
Should do what you expect.
If you work on a global context, you can also use:
array_key_exists('myNull', $GLOBALS);