目录 |
---|
一、流程控制 | 1.1 概念 / 1.2 分类 | 二、分支结构 | 2.1 if分支示例 / 2.2 switch分支示例 | 三、循环结构 | 四、循环控制(break / continue) | 五、输出九九乘法表示例 | 六、流程替换 |
一、流程控制
1.1 概念:流程控制就是代码执行的方向
1.2 分类:三个类
顺序结构
代码由上至下依次执行
分支结构( if 和 switch )
给定条件,按条件执行某一块代码
循环结构()
在某条件成立下,对指定代码块循环执行
二、分支结构 2.1 if分支示例
<?php
$day = 'Sunday';
if($day == 'Sunday'){
echo 'go to';
}
echo "<hr/>";
$day = 'Friday';
if($day == 'Sunday' || $day == 'Saturday'){
echo 'You can rest.';
}else{
echo 'You need to go to work.';
}
echo "<hr/>";
$day = 'Wednesday';
if($day == 'Monday'){
echo 'This is Monday.';
}else if($day == 'Tuesday'){
echo 'This is Tuesday.';
}else if($day == 'Wednesday'){
echo 'This is Wednesday.';
}else if($day == 'Thursday'){
echo 'This is Thursday.';
}else if($day == 'Friday'){
echo 'This is Friday.';
}else if($day == 'Saturday'){
echo 'This is Saturday.';
}else if($day == 'Sunday'){
echo 'This is Sunday.';
}
?>
if 分支执行效果如下:
2.2 switch分支示例
<?php
$day = 1;
switch ($day) {
case 1:
echo 'This is Monday.';
break;
case 2:
echo 'This is Tuesday.';
break;
case 3:
echo 'This is Wednesday.';
break;
case 4:
echo 'This is Thursday.';
break;
case 5:
echo 'This is Friday.';
break;
case 6:
echo 'This is Saturday.';
break;
case 7:
echo 'This is Sunday.';
break;
default:
echo 'This is not exist.';
break;
}
?>
switch 分支执行效果如下: 三、循环结构
<?php
echo "for" , '<br/>';
for($i = 1 ; $i <= 10 ; $i++){
echo $i,' ';
}
echo "<hr/>";
echo "while" , '<br/>';
$i = 1;
while($i <= 10){
echo $i , ' ';
$i++;
}
echo "<hr/>";
echo "do{}while()" , '<br/>';
$i = 1;
do{
echo $i , ' ';
$i++;
}while($i <= 10);
echo "<hr/>";
echo "foreach(){}" , '<br/>';
?>
四、循环控制(break / continue)
<?php
$i = 1;
while($i <= 100){
if($i == 80){break;}
if($i++ % 2 == 0){
continue;
}
echo $i-1 , ' ';
}
?>
五、输出九九乘法表
<table border="1">
<?php for($i = 1 ; $i < 10 ; $i++){ ?>
<tr>
<?php for($j = 1 ; $j <= $i ; $j++){ ?>
<td>
<?php echo $i . '*' . $j . '=' . $i*$j; ?>
</td>
<?php } ?>
</tr>
<?php } ?>
</table>
六、流程替换
<table border="1">
<?php for($i = 1 ; $i < 10 ; $i++): ?>
<tr>
<?php for($j = 1 ; $j <= $i ; $j++): ?>
<td>
<?php echo $i . '*' . $j . '=' . $i*$j; ?>
</td>
<?php endfor; ?>
</tr>
<?php endfor; ?>
</table>
|