用于基于不同条件执行不同的动作
if (条件) { 当条件为 true 时执行的代码; }
if (条件) { 条件为 true 时执行的代码; } else { 条件为 false 时执行的代码; }
if (条件) { 条件为 true 时执行的代码; } elseif (条件) { 条件为 true 时执行的代码; } else { 条件为 false 时执行的代码; }
<?php $t=date("H"); if ($t<"10") { echo "Have a good morning!"; } elseif ($t<"20") { echo "Have a good day!"; } else { echo "Have a good night!"; } ?>
switch (expression) { case label1: code to be executed if expression = label1; break; case label2: code to be executed if expression = label2; break; default: code to be executed if expression is different from both label1 and label2; }
<?php switch ($x) { case 1: echo "Number 1"; break; case 2: echo "Number 2"; break; case 3: echo "Number 3"; break; default: echo "No number between 1 and 3"; } ?>
在编写代码时,经常需要反复运行同一代码块,可以使用循环来执行这样的任务
while (条件为真) { 要执行的代码; }
<?php $sum = 12;//小宠物当前的饥饿程度 echo "我饿啦:-("; echo "<br />"; while($sum<100) {//小宠物的饥饿程度到100,表示小宠物吃饱啦,不用继续喂了,没吃饱继续喂食 $num = rand(1,20);//随机数,模拟喂食小宠物的小面包 $sum = $sum + $num; //小宠物吃小面包 echo "我还没吃饱呢!"; echo "<br />"; } echo "终于吃饱啦^_^"; ?>
循环首先会执行一次代码块,然后检查条件,如果指定条件为真,则重复循环
do { 要执行的代码; } while (条件为真);
<?php $sum = 0; do{ $num = rand(1,6);//获取1至6的随机数,模拟掷骰子 $sum = $sum + $num;//前进步长 }while($num==6); echo "do...while例子执行完毕,前进:".$sum ."<br />"; ?>
for循环语句中,初始化在循环开始前无条件求值一次,循环条件在每次循环开始前求值。如果值为true,则继续循环,执行循环体语句;如果值为false,则终止循环。递增语句在每次循环后执行
for (init counter; test counter; increment counter) { code to be executed; }
<?php for ($x=0; $x<=10; $x++) { echo "数字是:$x <br>"; } ?>
foreach循环只适用于数组,用于遍历数组中每个键/值对。每进行一次循环迭代,当前数组元素的值就会被赋值给$value变量,并且数组指针会逐一移动,直到到达最后一个数组元素。一般有两种方式:不取下标、取下标
[1]只取值,不取下标
foreach ($array as $value) { code to be executed; }
<?php $colors = array("red","green","blue","yellow"); foreach ($colors as $value) { echo "$value <br>"; } ?>
[2]同时取下标和值
foreach ($array as $index => $value) { code to be executed; }
<?php $colors = array( "r"=>"red", "g"=>"green", "b"=>"blue", "y"=>"yellow"); foreach ($colors as $key => $value) { echo $key.":".$value."<br>"; } ?>