Prev | Current Page 174 | Next

W. Jason Gilmore

"Beginning PHP and MySQL: From Novice to Professional"

What if you
want to provide a tailored response no matter the outcome? To do so you would need
100 CHAPTER 3 ?–  PHP B ASICS
a way to handle those not meeting the if conditional requirements, a function handily
offered by way of the else statement. Here??™s a revision of the previous example, this
time offering a response in both cases:
$secretNumber = 453;
if ($_POST['guess'] == $secretNumber) {
echo "

Congratulations!!

";
} else {
echo "

Sorry!

";
}
?>
Like if, the else statement brackets can be skipped if only a single code statement
is enclosed.
The elseif Statement
The if-else combination works nicely in an ???either-or??? situation??”that is, a situation
in which only two possible outcomes are available. But what if several outcomes are
possible? You would need a means for considering each possible outcome, which is
accomplished with the elseif statement. Let??™s revise the secret-number example
again, this time offering a message if the user??™s guess is relatively close (within ten)
of the secret number:
$secretNumber = 453;
$_POST['guess'] = 442;
if ($_POST['guess'] == $secretNumber) {
echo "

Congratulations!

";
} elseif (abs ($_POST['guess'] - $secretNumber) < 10) {
echo "

You're getting close!

";
} else {
echo "

Sorry!

";
}
?>
Like all conditionals, elseif supports the elimination of bracketing when only a
single statement is enclosed.


Pages:
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186