php循環語句for while do while的用法.
循環結構
一、while循環
- while(表達式)
- {
- 循環體;//反復執行,直到表達式為假
- }
- <?php
- $num = 1;
- while ($num <= 10){
- print "Number is $num<br />";
- $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 循環的比較,代碼如下:
- <?php
- for ($i=1; $i<=10; $i++) {
- echo "$i. 以后不敢了<br>n";
- }
- ?>
- //輸出表格
- <HEAD>
- <TITLE>Value of Shares</TITLE>
- <H3>Table Showing Cost of Shares</H3>
- <BODY>
- <TABLE BORDER=1>
- <?php
- for ($shares = 1; $shares <= 20; $shares++){
- $cost = $shares * 20;
- echo "<TR><TD>The cost of $shares share/s is $cost #x0024s</TD>","n";
- $dividend = $cost * 0.10;
- echo "<TD>The dividend is $dividend #x0024s</TD></TR> " ,"n";
- }
- ?>
- </TABLE>
- </BODY>
- </HTML>
累加計算,代碼如下:
- <?php
- $count = 1;
- while ($count < 5) {
- echo "$count squared = ".pow($count,2). "<br />";
- $count++;
- }
- ?>
do while 循環,代碼如下:
- <html>
- <head>
- <title>The do...while Statement</title>
- </head>
- <body>
- <div>
- <?php
- $num = 1;
- do {
- print "Execution number: $num<br />n";
- $num++;
- } while ( $num > 200 && $num < 400 );
- ?>
- </div>
- </body>
- </html>
新聞熱點
疑難解答