if-elseif-else结构
PHP也向你提供处理多个可能性的方法:if-elseif-else结构。典型的if-elseif-else语句块将看起来像下面所示:
if (first condition is true) {
do this!
}
elseif (second condition is true) {
do this!
}
elseif (third condition is true) {
do this!
}
... and so on ...
else {
do this!
}
此处为示范其如何使用的一个例子:
<html>
<head></head>
<body>
<h2>Today's Special</h2>
<p>
<form method="get" action="cooking.php">
<select name="day">
<option value="1">Monday/Wednesday
<option value="2">Tuesday/Thursday
<option value="3">Friday/Sunday
<option value="4">Saturday
</select>
<input type="submit" value="Send">
</form>
</body>
</html>
正如你所见,此为一简单的表单,该表单允许你自一周中挑选出一天。实际的工作由PHP脚本cooking.php来做:
<html>
<head></head>
<body>
![]()
<?php
// get form selection
$day = $_GET['day'];
// check value and select appropriate item
if ($day == 1) {
$special = 'Chicken in oyster sauce';
}
elseif ($day == 2) {
$special = 'French onion soup';
}
elseif ($day == 3) {
$special = 'Pork chops with mashed potatoes and green salad';
}
else {
$special = 'Fish and chips';
}
?>
![]()
<h2>Today's special is:</h2>
<?php echo $special; ?>
</body>
</html>
在该实例中,我使用if-elseif-else控制结构来根据不同的日子分配不同的菜单。请注意,一旦发现该块内的if()分支之一为真,则PHP将执行相应的代码,跳过该块内剩余的if()语句,然后立即跳转到整个if-elseif-else块后的代码行。
那么目前先到这里,参看更多关于条件语句的例子,请访问http://www.php.net/manual/en/language.control-structures.php。在第三章中,我将教给你更多控制结构、更多操作符及更多稀奇古怪的脚本。所以不要错过啊!
