深入了解
如果你一直用心学习,你会记得在第二章(http://tech.it168.com/o/2007-08-22/200708221043562.shtml,《PHP开发经典教程(Part 2): 操作符调用》)中,我曾给你上过PHP基本控制结构及操作符的快速速成课。我也向你展示了PHP如何用于处理输入Web表单中的数据。在本部分的教程中,我将深入讲解PHP操作符及控制结构,向你展示两个新的操作符,一种对条件语句if-else()系列结构的替代方法,以及PHP一些更为有趣的循环结构。因此请接着读下去,接下来的内容将会更加有趣!
在不同的情况之间切换
对控制结构的if-else()系列结构的一种替代方法是PHP的switch-case()语句,该switch-case()语句几乎可与if-else()控制结构做同样的事。其结构看起来如下面所示:
switch (decision-variable) {
case first condition is true:
do this!
case second condition is true:
do this!
... and so on...
}
<html>
<head></head>
<body>
![]()
<?php
![]()
// get form selection
$day = $_GET['day'];
// check value and select appropriate item
switch ($day) {
case 1:
$special = 'Chicken in oyster sauce';
break;
case 2:
$special = 'French onion soup';
break;
case 3:
$special = 'Pork chops with mashed potatoes and green salad';
break;
default:
$special = 'Fish and chips';
break;
}
![]()
?>
![]()
<h2>Today's special is:</h2>
<?php echo $special ?>
</body>
</html>