Conditions and Branches

Conditionals add control to scripts and permit choices. Different statements are executed depending on whether expressions are true or false. There are two branching statements in PHP: if, with the optional else clause, and switch, usually with two or more case clauses.

if...else Statement

The if statement conditionally controls execution. The basic format of an if statement is to test whether a condition is true and, if so, to execute one or more statements.

The following if statement executes the print statement and outputs the string when the conditional expression, $var is greater than 5, is true:

if ($var > 5)
    print "The variable is greater than 5";

Tip

The expressions used in the examples in this section compare integers. They can be used to compare strings but usually not with the expected results. If strings need to be compared, use the PHP string library function strcmp( ). It's discussed in more detail in Chapter 3.

Multiple statements can be executed as a block by encapsulating the statements within braces. If the expression evaluates as true, the statements within the braces are executed. If the expression isn't true, none of the statements are executed. Consider an example in which three statements are executed if the condition is true:

if ($var > 5)
{
    print "The variable is greater than 5.";

    // So, now let's set it to 5
    $var = 5;
    print "In fact, now it is equal to 5.";
}

Without the braces, an if statement executes only the single, immediately following ...

Get Web Database Applications with PHP and MySQL, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.