While Loops in PHP 在PHP裡的While迴圈

While Loops in PHP 在PHP裡的While迴圈

Looping the Loop 跑迴圈


A loop is a structure that tells a computer to execute a set of statements multiple times. If you have a process that you want repeated hundreds of times, it pays to put it in a loop so you don't need to write hundreds of lines of code.
迴圈其實就是告訴電腦重覆去執行某一組指令多次的一種結構。假如你有一個流程需要被重複執行上百次,最好就是將這些指令放進迴圈當中而不是重複寫上百次。

If you are working on these courses in order, you have already seen how a for loop can allow for a set number of loop iterations. But what about a situation where (due to randomness, perhaps) you don't know how many times the loop should repeat? In that case, you can use a while loop.
假如你是依序跟著我們的進度來學習,你應該已經看過for迴圈,它能讓你執行某一固定次數的迴圈。但是如果你無法確定次數哩?(因為隨機吧),就是說你在撰寫時並不確定迴圈該被重覆幾次,在這種情況下,你應該使用while迴圈。

A while loop will execute as long as a certain condition is true. For example, the loop in the editor will simulate coin flips as long as the number of consecutive heads is less than 3.
一個while迴圈將會不斷執行只要其狀態列(condition)為真。例如,編輯器的迴圈將會不斷執行只要硬幣連續丟出頭(H)面的次數小於3。


Instructions 操作指引

Take a look at the code in the editor and see if you understand how it will work. Once you think you know (or if you're stumped, no pressure!) click Save & Submit Code and see what happens. Check the hint if you would like an explanation.
看看編輯區裡的程式碼你是否能夠理解。假如你看得懂(如果不懂,也不要有壓力)按下Save& Submit Code來看看會發生什麼,如果需要一些解釋的話可以參考提示。


While Loop Syntax 迴圈While語法


In the last exercise, you saw how a while loop can be used to repeat a set of commands an unknown number of times. That loop used the following syntax:
在上一個練習,你看到while迴圈是如何地被用來重複執行固定但不確定次數的程式碼。迴圈使用如下的語法:



while(cond) {
  // looped statements go here
}

where the statements in side the curly braces { and } are executed as long as the condition cond is evaluated as true. In the last exercise, cond was the condition that the number of consecutive heads was less than 3: $headCount < 3.
寫在大括號裡頭的指令將會在狀態列cond為真時執行。在最後的練習,cond指的是狀態列其變數$headCount之值小於3。

It is important when writing loops to make sure that the loop will exit at some point.
在撰寫迴圈時,確保其有機會跳出迴圈是非常重要的。



while(2 > 1){
  // Code
}

The loop will never exit and is an example of an infinite loop. Avoid infinite loops like the plague! This is why we need to include $loopCond =false; in line 12. If you submit an infinite loop in one of these exercises, you will need to reload the page to stop it.
永遠無法結束的迴圈被稱為無窮迴圈。你應該極力避免產生無窮迴圈!而這也就是為什麼我們需要在第12行包含$loopCond = false ; 如果你在這些練習當中上傳一個無窮迴圈的話,你就必須要將頁面重載才能結束它。


Instructions 操作指引

Check out the while loop on line 9.
檢查第9行的while迴圈

- On line 9, add a condition inside the parentheses ( ) that makes the while loop run as long as $loopCond == true
- Inside the curly braces, use echo to output "<p>The loop is running.</p>"
- Then click Save & Submit Code to run your first PHP while loop!
- 在第9行,在小括號()裡頭加入狀態列。從而讓while迴圈能夠不斷執行只要 $loopCond == true
- 在大括號裡頭,使用echo來輸出"<p>The loop is running.</p>"
- 然後按下 Save & Submit Code 按鈕來運行你的第一個PHP While迴圈!


Your First While Loop 你的第一個While迴圈


Now it is time for you to write your own while loop from scratch. Maybe you could reproduce the behavior of one of your forloops from the previous course, or you could try to write your own coin flip program. The beauty of programming is that you can do whatever you want!
現在是時候讓你重頭撰寫你自己的while迴圈了。也許你可以再寫一次之前練習的內容,又或者是試著撰寫你自己的丟硬幣程式。程式最迷人之處就在於你可以做任何你想要的事!

Unless you want to write an infinite loop on purpose (which you don't!), do not write infinite loops! And if you find you have submitted one, refresh the page to stop it.
除非你真的想要試著撰寫無窮迴圈(最好不要),否則請避免撰寫無窮迴圈!如果你發現自己不小心上傳了一個無窮迴圈,請重載頁面來結束它。


Instructions 操作指引

Write the code for your own while loop below the comment inside the tags. Then click Save & Submit Code to see the results of your loop.
裡頭撰寫你自己的while迴圈。然後按下Save & Submit Code來送出並檢視結果。


Using Endwhile 使用Endwhile


PHP offers the following alternative syntax for while loops:
PHP提供以下的替代語法給while迴圈


while(cond):
  // looped statements go here
endwhile;

Note the colon after the end parenthesis and the semicolon after the endwhile statement.
記得小括號後面的冒號以及endwhile後面的分號。

When they are embedded in HTML, loops that use this endwhile syntax can be more readable than the equivalent syntax involving curly braces.
當程式碼被嵌在HTML裡頭時,迴圈使用endwhile這種語法比大括號版本的標準寫法提供更好的可讀性。就像下面這樣...


 while(cond) {
  // looped statements go here
  }

Feel free to use whichever syntax you prefer... except on this exercise!
你可以隨意的選擇自己喜歡的語法....當然,這一節的練習除外!


Instructions 操作指引

Convert your while loop from the last exercise into endwhile syntax. Then click Save & Submit Code to make sure your new loop works just like the old one.
將你最後一個練習的while迴圈變更成endwhile語法。然後按下 Save & Submit Code按鈕來確認結果是否與之前相同。


How Do You Do-While? 你如何使用Do-While?


You may have noticed that a while loop checks the loop condition before each iteration of the code inside. A logical alternative is to check the condition after each iteration before looping back. A do/whileloop does just that. One consequence of this difference is that the code inside a while loop can be bypassed entirely whereas the code inside a do/while loop will execute at least once.
你也許有注意到while迴圈會在執行遞迴區塊裡頭的程式碼之前先檢查狀態列。在邏輯上有另一種可能是在執行完遞迴區塊裡的程式碼之後才檢查狀態列。而do/while迴圈就是為此而生。因此產生了一個不同點在於while迴圈裡的遞迴程式可能完全沒被執行過而do/while迴圈則至少會被執行1次。

This means that the loop condition can depend exclusively on code within the loop's body. This is the case for the code in the editor where each iteration represents a coin flip, and any time the result of the coin flip is tails, the loop stops.
這表示迴圈狀態列的結果有可能會被遞迴程式產生影響。在編輯器裡的程式碼的每一次遞迴程式代表翻一枚硬幣,而當任何時候翻到T迴圈就會結束。


Instructions 操作指引

Inspect the code within the editor to see if you understand how it will work. If you don't, no worries! Click Save & Submit Code and see what happens.
檢視編輯器裡的程式碼看看自己是否能理解它是如何運作的。如果你有困難,別擔心!按下 Save & Submit Code來看看事情會怎麼運作。


Completing the Loop 完成迴圈


In the previous exercise, you saw how a do/while could be used to ensure that the code in a loop executed at least once. For example:
在之前的練習,你看到了 do/while 是如何的被利用以確保遞迴程式碼至少被使用1次。例如:


$i = 0;
do {
  echo $i;
} while ($i > 0);

This do / while loop only runs once and then exits:
這個 do / while 迴圈只會跑一次然後跳出:

- First we set $i equal to 0.
- 首先我們設定 $i等於0

- Second, the loop runs once and outputs $i, which is 0.
- 接著,迴圈跑1次然後輸出$i,其值為0。

- Then the condition while ($i > 0); is checked. Since $i is not greater than 0, the condition evaluates to false, andthedo/while` loop stops.
- 再接著,狀態列 while ($i > 0)會被檢查。只要 $i不大於0,狀態列結果為 false,則 do/while 迴圈就會停止。


Instructions 操作指引

Starting on line 9, there is a do / while loop that should run only once and then exit. But it's missing curly braces { }, parentheses ( ), and semicolons ;.
- 在第9行開始的地方,那是一個 do /while 迴圈,它應該只執行1次後就跳出。但它缺少了{ } . ( ) . 以及分號。
- Fill in the missing { }, ( ) and ; to make sure the do/while loop runs correctly. Check out the do / while loop above for an example.
- 補上大括號.小括號以及冒號,確保 do / while 迴圈能正常執行。可參考上面的 do /while 例子。
- Then click "Save & Submit Code" and verify that the page looks the way you expected.
- 然後按下 Save & Submit Code,確保頁面看起來是否如自己預期一般。


All On Your Own! 一切自己來!


Now it is time for you to write your own do/while loop. You could try to implement one of your for or while loops using a do/while structure, or you could try something completely different.
現在是你自己撰寫 do / while 迴圈的時候。你能夠試著用 do / while迴圈來實作先前所寫的 for 或 while迴圈,又或者是寫一個完全不同的。

But whatever you do, please do not write an infinite loop. And if you do submit one, refresh the page to stop it.
但無論你做什麼,請不要寫無窮迴圈。如果你上傳了無窮迴圈,重載頁面來停止它。


Instructions 操作指引

Create a do/while loop below the comment within the tags in the editor. Then click Save & Submit Code to make sure it behaves the way you think it should.
在編輯器裡頭建立一個 do / while迴圈。然後按下 Save & Submit Code並確保它如預期般執行。

分享這篇文章:

發佈自 林品爵

林品爵
一個堅信程式教育能夠改變下一代未來的狂熱者,青少年揚帆計畫的推動者。十年以上全端程式開發,上百場程式教學經驗,累積學生數達百人以上。 成大學士畢業,使用過J2EE.PHP.MySQL.CoronaSDK.Android.Objective-C.Swift.Python等技術知識,歷任友訊科技總部Java工程師首席.黑快馬股份有限公司研發經理.諾亞數碼娛樂執行長等職位,現任哥布林程式教育學苑創辦人,所開發過專案涵括產品管理系統.POS系統.拍賣平台.擴增實境.問券.社區等等。因觀察到學員英文不好產生挫折發展出布林程式教育系統。

關聯文章:

留下留言