if語句:
if(表達式1){
代碼段1
}elseif(表達式2){
代碼段2
}elseif(表達式3){
代碼段3
}else{
代碼段4
}
需要注意,如果執行到了代碼段3,說明表達式1和表達式2均不成立,並且表達式3成立,而不是僅僅是表達式3成立。分支語句:
switch分支語句(執行結構清晰,效率高):
switch(表達式){
case 值1:
...
break;
case 值2:
...
break;
default:
...
}
循環語句:
while語句:
while(){
語句;
}
max_execution_time = 30
也可以直接使用系統內置的限制函數:
$x = 1;
while($x){
echo $x++."<br/>";
}
set_time_limit(10);
foreach($arr as $k=>$v):
語句1;
語句2;
...
endforeach;
這種寫法適用於while、for、foreach、switch。
<style>
.bg_red{background-color:#f00; color:#fff;}
</style>
<?php
$mysqli = new mysqli('localhost', 'root', '','edu');
$i = 1;
while($i<=100){
$sql = "insert into user (uname,age) values('qizhi{$i}',$i)";
$mysqli->query($sql);
$i++;
}*/
$sql = "select * from user order by age";
$result = $mysqli->query($sql);
echo "<table>";
while($row = $result->fetch_assoc()){
if($row['age']>30){
echo "<tr class='bg_red'>";
}else{
echo "<tr>";
}
echo "<td>姓名:".$row['uname']."</td><td>\t年齡:".$row['age']."</td>";
echo "</tr>";
}
echo "</table>";
?>
結果:
姓名:qizhi1 年齡:1
姓名:qizhi2 年齡:2
……
姓名:qizhi98 年齡:98
姓名:qizhi99 年齡:99
姓名:qizhi100 年齡:100
九九乘法表:
$i = 1;
while($i<=9){
$j = 1;
while($j<=$i){
echo $j.'*'.$i.'='.$i*$j."\t";
$j++;
}
echo "<br/>";
$i++;
}
結果:
1*1=1
1*2=2 2*2=4
1*3=3 2*3=6 3*3=9
1*4=4 2*4=8 3*4=12 4*4=16
1*5=5 2*5=10 3*5=15 4*5=20 5*5=25
1*6=6 2*6=12 3*6=18 4*6=24 5*6=30 6*6=36
1*7=7 2*7=14 3*7=21 4*7=28 5*7=35 6*7=42 7*7=49
1*8=8 2*8=16 3*8=24 4*8=32 5*8=40 6*8=48 7*8=56 8*8=64
1*9=9 2*9=18 3*9=27 4*9=36 5*9=45 6*9=54 7*9=63 8*9=72 9*9=81
稍微修改一下就是這樣:
1*1=1 | ||||||||
1*2=2 | 2*2=4 | |||||||
1*3=3 | 2*3=6 | 3*3=9 | ||||||
1*4=4 | 2*4=8 | 3*4=12 | 4*4=16 | |||||
1*5=5 | 2*5=10 | 3*5=15 | 4*5=20 | 5*5=25 | ||||
1*6=6 | 2*6=12 | 3*6=18 | 4*6=24 | 5*6=30 | 6*6=36 | |||
1*7=7 | 2*7=14 | 3*7=21 | 4*7=28 | 5*7=35 | 6*7=42 | 7*7=49 | ||
1*8=8 | 2*8=16 | 3*8=24 | 4*8=32 | 5*8=40 | 6*8=48 | 7*8=56 | 8*8=64 | |
1*9=9 | 2*9=18 | 3*9=27 | 4*9=36 | 5*9=45 | 6*9=54 | 7*9=63 | 8*9=72 | 9*9=81 |
do...while
do{
代碼段;
}while(條件);
for循環:
for(初始化;判斷條件;遞增){
代碼段;
}
在一些特殊條件下,括號中的表達式可以省略(分號不能省略)。
break:
$i = $j = 1;
while($i++<10){
echo '$i='.$i;
while($j++<5){
echo ' $j='.$j;
if($j==3) break 2; //表示退出兩層循環
}
echo "<br/>";
}
continue:
continue 2;
表示跳出兩層循環到循環結尾,繼續下次循環(如果循環還沒有結束的話)。die 和 exit:
echo "1111";
exit(0);
echo "2222"; //不會執行,因爲在exit已退出
當程序出錯時,可以給它傳遞一個字符串,它會原樣輸出在系統終端上,通常使用die()。
$fp=fopen("./readme.txt","r") or die("不能打開該文件");
也可以直接使用exit語句和die語句直接退出腳本:
die;
exit;