Wednesday, 8 July 2015

Using the else Clause with the if Statement

When working with the if statement, you will often want to define an alternative
block of code that should be executed if the expression you are testing evaluates to
false. You can do this by adding else to the if statement followed by a further block
of code:
if ( expression )
{
// code to execute if the expression evaluates to true
}
else
{
// code to execute in all other cases
}
Listing 5.2 amends the example in Listing 5.1 so that a default block of code is
executed if $mood is not equivalent to "happy".
Listing 5.2: An if Statement That Uses else
1: <html>
2: <head>
3: <title>Listing 5.2</title>
4: </head>
5: <body>
6: <?php
7: $mood = "sad";
8: if ( $mood == "happy" )
9: {
10: print "Hooray, I'm in a good mood";
11: }
12: else
13: {
14: print "Not happy but $mood";
15: }
16: ?>
17: </body>
18: </html>
$mood contains the string "sad", which is not equivalent to "happy", so the
expression in the if statement evaluates to false. This means that the first block of
code is skipped. The block of code after else, therefore, is executed, and the
message "Not happy but sad" is printed to the browser.
Using the else clause with the if statement allows scripts to make sophisticated
decisions, but you currently are limited to an either -or branch. PHP4 allows you to
evaluate multiple expressions in a cascade.
Using the elseif Clause with the if Statement
You can use an if-elseif-else construct to test multiple expressions before offering a
default block of code:
if ( expression )
{
// code to execute if the expression evaluates to true
}
elseif ( another expression )
{
// code to execute if the previous expression failed
// and this one evaluates to true
else
{
// code to execute in all other cases
}
If the first expression does not evaluate to true, then the first block of code is
ignored. The elseif clause then causes another expression to be evaluated. Once
again, if this expression evaluates to true, then the second block of code is executed.
Otherwise, the block of code associated with the else clause is executed. You can
include as many elseif clauses as you want, and if you don't need a default action,
you can omit the else clause.

No comments:

Post a Comment