How to check if a variable exists in PHP

Go ahead, look at the PHP type comparison tables and snicker over how the language is a cobbled-together hack. I still love it, but I did run into a little bit of confusion today. Here is the basic issue:

$a = null;
//$b = 42;

Simple enough; $a is set to null and $b is commented out and therefore does not exist. The problem is that I could not find an easy way to differentiate between those two states. Sadly, isset() returns false when a variable has been set to null. I scanned over the function list and googled around some, but could not find the sort of exists() or is_defined() function that I wanted.

Amusingly, is_null() returns true for both $a and $b, but PHP will spit out a notice about an “undefined variable” when you do is_null($b) (depending on your error_reporting configuration). So PHP knows the difference between a null’ed variable and one that has never been set… but how do I get access to that knowledge?

The best way I could find was to use get_defined_vars(). For example:

$a = null;
//$b = 42;
$arr = get_defined_vars();
if (array_key_exists('a', $arr)) echo "Yes, \$a exists!\n";
if (array_key_exists('b', $arr)) echo "This will not print.\n";

If anyone knows of a better way to do this, I’d love to hear it.

This entry was posted in HOW-TOs, Programming. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *