跳轉到內容

PHP 程式設計/do while 迴圈

來自華夏公益教科書,開放的書籍,面向開放的世界

do while 迴圈

[編輯 | 編輯原始碼]

do while 迴圈在語法和目的上類似於 while 迴圈。do/while 迴圈結構將繼續迴圈的測試移至程式碼塊的末尾。程式碼至少執行一次,然後測試條件。例如

<?php
$c = 6;
do {
  echo 'Hi';
} while ($c < 5);
?>

即使 $c 大於 5,指令碼也會將 "Hi" 輸出到頁面一次。

PHP 的 do/while 迴圈並不常用。

此示例將輸出 $number階乘(從 1 到它的所有數字的乘積)。

PHP 程式碼:

$number = 5;
$factorial = 1;
do {
  $factorial *= $number;
  $number = $number - 1;
} while ($number > 0);
echo $factorial;

PHP 輸出:

120

HTML 渲染:

120


continue 語句

[編輯 | 編輯原始碼]

continue 語句會導致當前迴圈迭代結束,並繼續在檢查條件的地方執行 - 如果該條件為真,則重新開始迴圈。例如,在迴圈語句中

<?php
$number = 6;
for ($i = 3; $i >= -3; $i--) {
  if ($i == 0) {
    continue;
  }
  echo $number . " / " . $i . " = " . ($number/$i) . "<br />";
}
?>

當條件 i = 0 為真時,語句不會執行。

更多資訊

[編輯 | 編輯原始碼]


華夏公益教科書