How can I check if a variable is defined?

if (isset($var)) {
echo “the var is set, and equals $var. It may be empty though.”;

isset() will tell you is a varaible has been defined. This can bite some
users, because it will return true even if the varable has an empty
value. Look at empty() as well. Sometimes you’ll want to use one rather
than the other. Note that even “0” and 0 are considered empty.

For example, say I have an HTML form that passes various form
elements. Even when a user leaves one blank, the variable is still be
set, so isset() will return true. empty() will also return true as
it’s empty, even though it’s set. But also note that since PHP 4, if
someone enters in the value 0 into a form, it’s also seen as empty.

For a useful type comparisons chart of isset() vs empty() vs many other
functions and syntax, see this appendix:

if (isset($var)) {
    echo "the var is set, and equals $var.  It may be empty though.";

One Comment

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.