Overview
The scripts created in the last hour flow only in a single direction. The same
statements are executed in the same order every time a script is run. This does not
leave much room for flexibility.
You now will look at some structures that enable your scripts to adapt to
circumstances. In this hour, you will learn
How to use the if statement to execute code only if a test expression evaluates
to true
How to execute alternative blocks of code when the test expression of an if
statement evaluates to false
How to use the switch statement to execute code based on the value returned by
a test expression
How to repeat execution of code using a while statement
How to use for statements to make neater loops
How to break out of loops
How to nest one loop within another
Switching Flow
Most scripts evaluate conditions and change their behavior accordingly. The facility
to make decisions makes your PHP pages dynamic, capable of changing their output
according to circumstances. Like most programming languages, PHP4 allows you to
do this with an if statement.
The if Statement
The if statement evaluates an expression between parentheses. If this expression
results in a true value, a block of code is executed. Otherwise, the block is skipped
entirely. This enables scripts to make decisions based on any number of factors.
if ( expression )
{
// code to execute if the expression evaluates to true
}
Listing 5.1 executes a block of code only if a variable contains the string "happy".
Listing 5.1: An if Statement
1: <html>
2: <head>
3: <title>Listing 5.1</title>
4: </head>
5: <body>
6: <?php
7: $mood = "happy";
8: if ( $mood == "happy" )
9: {
10: print "Hooray, I'm in a good mood";
11: }
12: ?>
13: </body>
14: </html>
You use the comparison operator == to compare the variable $mood with the string
"happy". If they match, the expression evaluates to true, and the code block below
the if statement is executed. Although the code block is wrapped in braces in the
example, this is only necessary if the block contains more than one line. The
following fragment, therefore, would be acceptable:
if ( $mood == "happy" )
print "Hooray, I'm in a good mood";
If you change the value of $mood to "sad" and run the script, the expression in the
if statement evaluates to false, and the code block is skipped. The script remains
sulkily silent.
No comments:
Post a Comment