Skip to Main Content
PHP in a Nutshell
book

PHP in a Nutshell

by Paul Hudson
October 2005
Intermediate to advanced content levelIntermediate to advanced
372 pages
11h 35m
English
O'Reilly Media, Inc.
Content preview from PHP in a Nutshell

Conditional Statements

PHP allows you to choose what action to take based on the result of a condition. This condition can be anything you choose, and you can combine conditions to make actions that are more complicated. Here is a working example:

    <?php
            $Age = 20;
            if ($Age < 18) {
                    print "You're young - enjoy it!\n";
            } else {
                    print "You're not under 18\n";
            }

            if ($Age >= 18 && $Age < 50) {
                    print "You're in the prime of your life\n";
            } else {
                    print "You're not in the prime of your life\n";
            }

            if ($Age >= 50) {
                    print "You can retire soon - hurrah!\n";
            } else {
                    print "You cannot retire soon :( ";
            }
    ?>

At the most basic level, PHP evaluates if statements left to right, meaning that it first checks whether $Age is greater or equal to 18, then checks whether $Age is less than 50. The double ampersand, &&, means that both statements must be true if the print "You're in the prime of your life\n" code is to be executed—if either one of the statements is not true for some reason, "You're not in the prime of your life" is printed out instead. The order in which conditions are checked varies when operator precedence matters; this is covered in the next chapter.

As well as &&, there is also || (the pipe symbol printed twice) which means OR. In this situation, the entire statement is evaluated as true if any of the conditions being checked is true.

There are several ways to compare two numbers. We have just looked at < (less than), <= (less than or equal to), and >= (greater than or equal to). We will ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Cookbook

PHP Cookbook

Eric A. Mann
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe
Learning PHP

Learning PHP

David Sklar

Publisher Resources

ISBN: 0596100671Errata Page