PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!
<?
$var = "";
if (isset($var))
{
print "the variable is set";
}
else
{
print "the variable i not set";
}
?>
You'll see you get two different results. The first one equates to true becuase the variable is set to nothing, whereas the second one equates to false.
I have a test.php page which I can't lay my hands on right now so I can't write up something with all the ins and outs.
Basically, the test file runs through all conceivable options for $var = 0, false, true, null, ''(empty string) and so on and outputs the result of isset, empty etc. I'd highly recommend you set something up like that to investigate - and the user comments in the php manual are also helpful.
Personally, I always use isset() when i want to check the whether a variable has a value. You never know when something might screw up, so it's better to have functioonal reassurance (isset() rather then if($var)). Although, the only time I ever use that function is to check a variable from the address bar. for example:
It's interesting, this thread. Recently on the PHP development list, someone proposed a function called variable_exists(). After that, an eruption of chatter occured about the vaugness of PHP and null verses 0 and all kinds of other stuff.
Anyways, as some have pointed out in a less direct manner, you can have an empty var. That said, be careful what it is you are testing for. Emptiness or existence? That said, just becuase it exists, don't assume it's not empty. My arse is full of scars behind (no pun intended) this issue. Sure, it's a subtle distinction, but an important one.
is that the first will give you a warning (if, as you should have for development, your error reporting is at its highest level). Basically if you want to test whether a variable exists don't use the first method.