發新話題

[分享] While和Do While迴圈 [PHP教學]

While和Do While迴圈 [PHP教學]

while 迴圈是 PHP 裏最簡單的迴圈形式。 和 c 的 while 一樣, 它基本的句式是:

while (expr) statement

while 的意思很直接: 只要它的條件表達式成立, 它會叫 PHP 不停地執行 while 之內的指令。 因為每次 while 之內的指令全部執行後都會檢查一次 while 條件是否依然成立, 所以就算條件在指令之時已經改變,但都要等所有指令都完成後才會跳出迴圈。(每次執行完迴圈中所有的指令都叫做完成了一次循環) 假如 while 表達式在一開始的時候就不成立,那 while 之中的指令根本不會被執行 (零次循環)。

和 if 一樣, 你可以把好多指令用 '{ }' 包起來放在while 迴圈之中。 你也可以用 while 的等效句法來寫:

while (expr): statement ... endwhile;

下面兩個示範將產生相同的結果: 把 1 到 10 印出來
/* example 1 */

$i = 1;
while ($i <= 10) {
    print $i++;  /* the printed value would be
                    $i before the increment
                    (post-increment) */
}

/* example 2 */

$i = 1;
while ($i <= 10):
    print $i;
    $i++;
endwhile;

Due to the fact that php only interprets the necessary elements to get a result, I found it convenient to concatenate different sql queries into one statement:

<?php

$q1 = 'some query on a set of tables';
$q2 = 'similar query on a another set of tables';

if ( (($r1=mysql_query($q1)) && ($r2=mysql_query($q2)) ) {

     while (($row=mysql_fetch_assoc($r1))||($row=mysql_fetch_assoc($r2))) {

         /* do something with $row coming from $r1 and $r2 */

      }
   }

?>

TOP

發新話題

本站所有圖文均屬網友發表,僅代表作者的觀點與本站無關,如有侵權請通知版主會盡快刪除。