Checking a variable is set

Although the majority of functions are covered in in the Functions chapter, you really need to get to grips with the isset() function (literally "is a variable set?") in order to make the most of this chapter. To make it work, you pass a variable in as the only parameter to isset(), and it will return true or false depending on whether the variable is set. For example:

<?php
    $foo
= 1;
    if (isset(
$foo)) {
        echo
"Foo is set\n";
    } else {
        echo
"Foo is not set\n";
    }
    if (isset(
$bar)) {
        echo
"Bar is set\n";
    } else {
        echo
"Bar is not set\n";
    }
?>

That will output "Foo is set" and "Bar is not set". Usually if you try to access a variable that isn't set, like $bar above, PHP will issue a warning that you are trying to use an unknown variable. This does not happen with isset(), which makes it a safe function to use.

As I said, flip ahead to the Functions chapter to read more about this function; for now, you just need to know this one.

Note that throughout this book (and throughout the programming world), "nonsense" variable names are used. Names like $foo, $bar, and $baz are the most common, but I often add $wom and $bat. Some argue against the use of these names, but the reality is that their use is so widespread - and that they can help liven up otherwise dull texts - and so I've used them liberally. That said, avoid them in your own code unless it's for short-lived variables.

 

Next chapter: Automatic type conversion >>

Previous chapter: Types of Data

Jump to:

 

Home: Table of Contents

Follow us on Identi.ca or Twitter

Username:   Password:
Create Account | About TuxRadar