一、while循环

while(表达式)

{

循环体;//反复执行,直到表达式为假

}


代码:

$index = 1;

while ($index<5)

{

print "Number is {$index} ";

$index++;

}


运行结果:

Number is 1

Number is 2

Number is 3

Number is 4



二、do while循环

do {

循环体;//反复执行,直到表达式为假

} while(表达式)


代码:

do {

$index++;

print "Number is {$index} ";

} while($index<0);


运行结果:

Number is 1



Do While 循环语句与while有一定的区别,它们的区别就是do while不管条件是否为真都会先执行一下,而while必须为真才会执行一次.


三、for循环

根据循环条件不同,有两种类型的循环

一种:计数循环 (一般使用for)

另一种:条件型循环 (一般使用 while do-while)

for (expr1; expr2; expr3) {

statement

}

其中的 expr1 为条件的初始值。expr2 为判断的条件,通常都是用逻辑运算符号 (logical operators) 当判断的条件。expr3 为执行 statement 后要执行的部份,用来改变条件,供下次的循环判断,如加一..等等。而 statement

为符合条件的执行部分程序,若程序只有一行,可以省略大括号 {}。

下例是用 for 循环写的 "以后不敢了" 的例子,可以拿来和用 while 循环的比较。

<?php

for ($i=1; $i<=10; $i++) {

echo "$i. 以后不敢了 <br />";

}

?>


运行结果:

1. 以后不敢了

2. 以后不敢了

3. 以后不敢了

4. 以后不敢了

5. 以后不敢了

6. 以后不敢了

7. 以后不敢了

8. 以后不敢了

9. 以后不敢了

10. 以后不敢了


四、foreach循环


foreach 语句用于循环遍历数组。每进行一次循环,当前数组元素的值就会被赋值给 value 变量(数组指针会逐一地移动) - 以此类推


语法:

foreach (array as value)

{

code to be executed;

}

代码:

<?php

$arr=array("one", "two", "three");


foreach ($arr as $value)

{

echo "Value: " . $value . " ";

}

?>


运行结果:

Value: one

Value: two

Value: three

以上为PHP中四种循环体,根据不同的条件选择相应的循环体运用