php循环语句for while do while的用法.
循环结构
一、while循环
- while(表达式)
- {
- 循环体;//反复执行,直到表达式为假
- }
- $num = 1;
- while ($num <= 10){
- print "Number is $num
";- $num++;
- }
- print 'Done.';
- ?>
Do While 循环语句与while有一定的区别,它们的区别就是do while不管条件是否为真都会先执行一下,而while必须为真才会执行一次.
- do {
- echo "Mmmmm...I love cookies! *munch munch munch*";
- } while ($cookies > 1);
- //输出就是.
- //Mmmmm...I love cookies! *munch munch munch
二、for循环
根据循环条件不同,有两种类型的循环
一种:计数循环(一般使用for)
另一种:条件型循环,一般使用 while do-while.
- for (expr1; expr2; expr3) {
- statement
- }
其中的 expr1 为条件的初始值,expr2 为判断的条件,通常都是用逻辑运算符号 (logical operators) 当判断的条件,expr3 为执行 statement 后要执行的部份,用来改变条件,供下次的循环判断,如加一..等等,而 statement 为符合条件的执行部分程序,若程序只有一行,可以省略大括号 {}.
下例是用 for 循环写的 "以后不敢了" 的例子,可以拿来和用 while 循环的比较,代码如下:
- for ($i=1; $i<=10; $i++) {
- echo "$i. 以后不敢了
n";- }
- ?>
- //输出表格
Value of Shares Table Showing Cost of Shares
- for ($shares = 1; $shares <= 20; $shares++){
- $cost = $shares * 20;
- echo "
" ,"n"; The cost of $shares share/s is $cost #x0024s ","n";- $dividend = $cost * 0.10;
- echo "
The dividend is $dividend #x0024s - }
- ?>
累加计算,代码如下:
- $count = 1;
- while ($count < 5) {
- echo "$count squared = ".pow($count,2). "
";- $count++;
- }
- ?>
do while 循环,代码如下:
The do...while Statement - $num = 1;
- do {
- print "Execution number: $num
n";- $num++;
- } while ( $num > 200 && $num < 400 );
- ?>




