Microsoft Word - Core PHP Programming Using PHP to Build Dynamic Web Sites

(singke) #1

Chapter 3. CONTROL STATEMENTS


Control statements allow you to execute blocks of code depending on conditions. They
also allow you to repeat a block of code, which leads to simpler, more efficient scripts.
This chapter will introduce you to the decision-making statements if and switch. You
will also learn about loops using for and while.


True and False


As you remember from Chapter 2, PHP has the concepts of true and false. Zero and an
empty string are considered to be false. Any other numerical value or string is true. These
concepts were discussed in regard to relational operators, but they are also used in control
statements. Control statements like if expect a boolean value, so any value they are
given will be converted to a boolean.


The if Statement


Figure 3-1 lays out the form of an if statement.


Figure 3-1. The form of an if statement.

The if statement executes a statement if the expression inside the parentheses evaluates
to true; otherwise the code is skipped. It may be a single statement followed by a
semicolon. Usually it's a compound statement surrounded by curly braces. An else
statement may appear immediately after the statement and has a statement of its own. It,
too, may be either single or compound. It is executed only when the previous expression
is false. In between an if statement and an else statement you may put as many elseif
statements as you'd like. Each elseif expression is evaluated in turn, and control skips
past those that are false. If an elseif statement evaluates to true, then the rest of the

Free download pdf