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.

 

Want to learn PHP 7?

Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!

If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!

Next chapter: Automatic type conversion >>

Previous chapter: Types of Data

Jump to:

 

Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.