流程控制语句
一、条件控制语句
if 、if ....else 、if ...elseif ....elseif ...else 、switch....case。
1.1范例:if....elseif ....else
1 <?php 2 $num = rand(1,31); 3 if($num%2==0){ 4 echo “num能被2整除!”; 5 } 6 elseif($num%3==0){ 7 echo "num能被3整除!"; 8 } 9 else 10 echo "num不能被2和3整除!"; 11 ?>
1.2 switch ....case范例:
1 <?php 2 switch($_GET[Imbs]){ 3 case "最新商品": 4 include "new.php"; 5 break; 6 case "热门商品": 7 include "jollification.php"; 8 break; 9 default: 10 include "new.php"; 11 break;
} 12 ?>
二、循环控制语句
2.1 while语句范例:
<?php $num = 1; while($num<=10){ $num +=1; echo "\$num = $num"; } ?>
2.2 do...while语句范例
1 <?php 2 $num = 1; 3 do{ 4 $num +=1; 5 echo "\$num = $num"; 6 } while($num<=10) 7 ?>
2.3 for语句范例
1 <?php 2 $num = 1; 3 for($i=0;$i<10;$i++){ 4 $num +=1; 5 echo "\$num = $num"; 6 } 7 ?>
2.4 foreach语句
foreach(array_express as $value)
statement;
foreach循环语句将遍历数组array_expression.每次循环时,将当前数组中的值赋值给$value(或$key和$value),同时,数组指针向后移动直到遍历结束。
范例:
1 <?php 2 $arr = array(1, 2, 3, 4); 3 foreach ($arr as $value) { 4 $value = $value * 2; 5 } 6 // $arr is now array(2, 4, 6, 8) 7 ?>
break continue关键字
break可以跳出多重循环,continue可以跳出多次循环。
brake范例:
1 <?php 2 function example1(){ 3 static $m = 2; 4 $m+=1; 5 return $m; 6 } 7 for($i=0;$i<5;$i++) 8 { 9 for($i=0;$i<10;$i++) 10 {echo example1()."<p>"; 11 break 2; 12 } 13 echo "good!<br>"; 14 } 15 echo ($a=="hello!")?1:2; 16 ?>
continue范例:
1 <?php 2 function example1(){ 3 static $m = 2; 4 $m+=1; 5 return $m; 6 } 7 for($i=0;$i<5;$i++) 8 { 9 for($i=0;$i<10;$i++) 10 {echo example1()."<p>"; 11 continue 2; 12 } 13 echo "good!<br>"; 14 } 15 echo ($a=="hello!")?1:2; 16 ?>