For Loops in PHP 迴圈

For Loops in PHP 迴圈

What's a Loop 什麼是迴圈?


Programming can be tough work, and sometimes it's made tougher by having to do the same thing over and over. Let's say we want to echo a list of leap years in the editor. You might think we'd have to type:
程式開發有時很辛苦,特別是當需要不停的重複相同工作的時候。比方說要在編輯上"echo"出閏年,你也許以為我們必須要一行行的打下去...



echo 2004; echo 2008; echo 2012; // And so on

But there's a better way!
但其實生命自有其出口!

A loop is a useful bit of code that repeats a series of instructions for you. For instance, instead of typing echo many times like we did above, we can simply use the code in the editor to the right!
迴圈當需要在程式中重覆執行一系列操作時特別管用。舉例來說,除了如上例這樣一行行的輸入以外,透過撰寫迴圈也可以達到相同目的。


Instructions 操作指引

Check out the for loop in the editor. See how it echos the value for $leap, adds four to it, then repeats? Click Save & Submit Code to learn how it all works!
看一下for迴圈結構。看看 $leap的值是如何被印出來的,猜猜它又是為什麼會4年一跳?最後按下Save & Submit Code進到下一章節來學習更多細節!

'For' Loop Syntax For迴圈語法


Cool, right? Let's go through the syntax slowly, step-by-step. Here's an example that just echos the numbers 0 to 9:
很酷,不是嗎?讓我們慢慢來,逐步的審視語法。這裡給出一個例子利用echo來印出數字0到9



for ($i = 0; $i < 10; $i++) {
  echo $i;
}
// echoes 0123456789

It breaks down like this:
拆解結果如下:

- A for loop starts with the forkeyword. This tells PHP to get ready to loop!
For迴圈開始於for關鍵字。這告訴PHP迴圈的開始!

- Next comes a set of parentheses (()). Inside the parentheses, we tell PHP three things, separated by semicolons (;): where to start the loop; where to end the loop; and what to do to get to the next iteration of the loop (for instance, count up by one).
接下來是一組的( )。在小括號裡頭,我們告訴 PHP三件事情並透過分號( ; )來分開,分別為:從何開始迴圈 ; 從何結束迴圈 ; 迴圈每一輪的索引值要增加或減少多少(例如每輪加1)

- After the part in parentheses, the part in curly braces ({}) tells PHP what code to run for each iteration of the loop.
- 在小括號之後, { } 裡頭的部分告訴PHP在每一輪迴圈裡的程式實作內容。

So the above example says: "Start looping with $i at 0, stop the loop before $i gets to 10, count up by 1 each time, and for each iteration, echo the current value of $i.” 那麼上面的例子表示:迴圈起始時$i為0,迴圈結束時$i為10,每次加1,並在每次迴圈過程中,印出當前的$i值。

($i++ is shorthand for $i = $i + 1. You'll see this a lot!)
$i++$i = $i + 1的簡寫。你之後將會常見到這樣的寫法!


Instructions 操作指引


Complete the for loop in the editor by replacing the ___s with the correct loop syntax. Use the example in the instructions as a guide!
透過將底線替換成正確的迴圈語法來完成編輯器裡的For迴圈。可以參考上面的例子!


Writing Your First 'For’ Loop 撰寫你的第一個For迴圈


Great work! Now let's put together our first for loop from start to finish.
幹得好!現在從頭到尾檢視一下我們的第一個for迴圈。

A for loop that prints out the numbers 1 through 10 might look something like this:
一個用來印從1到10的數字的迴圈應該看起來像這樣:



for ($i = 0; $i < 11; $i++) {
  echo $i;
}

This for loop counts up by 1 each time, all the way to 10.
這個for迴圈每輪索引值加1,一直到10。

You could change the third part of the forloop so that it counts up by 5 instead, like this:
你能夠修改for迴圈的第三部分讓它變成每次加5,像這樣:



for ($i = 0; $i < 11; $i = $i + 5) {
  echo $i;
}

Instead of $i++, we have $i = i + 5 to count up by 5, all the way to 10.
我們用 $i = $i + 5 來取代 $i++ 來讓索引值每次加5,一直到10。


Instructions 操作指引


Write a for loop that counts up by 10, all the way to 100 (e.g. 10, 20, 30...). Inside the for loop, echo the current value of $i, just like in the examples above.
寫一個for迴圈,索引值每次加10一直到100(例如:10,20,30...)。在迴圈裡頭用echo印出當前的$i值,就如同之前的例子。


When to Use ‘For' 何時要使用For迴圈


Great job! for loops are great for running the same code over and over, especially when you know ahead of time how many times you'll need to loop. (There are other kinds, such as while and do/while loops, that we can use when we don't know ahead of time how many times we'll need to loop, but we'll cover those in a later lesson.) 幹得好! For迴圈很適合用來一次又一次的執行重複的程式碼,特別當你知道總共要執行幾次時。(其實還有其他種類的迴圈,像是while以及do/while,適合用在不清楚迴圈需要執行幾次的場合,但我們將會在之後的章節來說明)。

There's also a special kind of loop called a foreach loop that we can use to update or print out every element in a list—for example, an array. Let's cover foreachnext!
這裡還有一種特殊的迴圈稱為foreach 可以用來變更或印出列表裡的每一個元素。例如,一個迴圈。讓我們下一章來說明!


Loops + Arrays = ForEach 迴圈 + 陣列 等於 ForEach


The foreach loop is used to iterate over each element of an object—which makes it perfect for use with arrays!
這個foreach是用來依序取出物件裡的每一個元素—這個特性讓它極為適合用在陣列裡面!

You can think of foreach as jumping from element to element in the array and running the code between {}s for each of those elements.
你可以想像foreach會依序取出陣列裡的每一個元素,然後在 { }裡頭處理或應用這些元素。


Instructions 操作指引


Check out the code in the editor. See how the $lang variable takes on the value of each of the elements in $langs, one by one, then echos that element to the page?
檢查編輯器裡的程式碼。看看$lang是如何儲存從$langs取出的元素,一個接一個,然後在頁面上echo這些元素?

Click Save & Submit Code to learn how it all works!
沒問題的話就按下 Save & Submit Code!


Practicing with ForEach 練習ForEach


Let's walk through the foreach syntax step-by-step. First, here's a foreach loop that iterates over an array and prints out each element it finds:
來逐步檢視foreach的語法。首先,foreach迴圈會遍歷一個陣列並印出取出的每個元素:



  $numbers = array(1, 2, 3);

  foreach($numbers as $item) {
  echo $item;
  }

First, we create our array using the array()syntax we learned in the last lesson.
首先,我們利用從上一個章節所學到的array()語法來建立一個陣列。

Next, we use the foreach keyword to start the loop, followed by parentheses. (This is very similar to what we've done with forloops.)
接著,使用foreach來開始一個迴圈,接著一對大括號。(這結構與之前提及的for迴圈極為類似)

Between the parentheses, we use the $numbers as $item) syntax to tell PHP: "For each thing in $numbers, assign that thing temporarily to the variable $item." (We don't have to use the name $item—just as with for loops, we can call our temporary variable anything we want.)
在大括號之間,我們使用$numbers as $item語法來告訴PHP:”逐一取出$numbers裡的元素,並暫時賦值給$item變數。”(我們不一定要將此變數命名為$item —就如同For迴圈,我們可以任意宣告暫用變數為任意名字)

Finally, we put the code we want to execute between the curly braces. In this case, we just echo each element in turn.
最後,我們將想要執行的內容放在大括號裡頭。在這裡例子裡頭,我們只是echo每一輪所取出的元素。


Instructions 操作指引


Complete the foreach loop in the editor by replacing the ___s with the correct loop syntax. Use the example in the instructions as a guide!
透過將__替換成正確的迴圈語法來完成foreach。請參考先前的例子!


All On Your Own! 現在自己來!


Great work! Now let's see you write a foreach loop all on your own.
幹得好!現在讓你自己寫一個foreach迴圈。


Instructions 操作指引


On line 8, there's an array named $yardlines. Write a foreach loop that iterates over the array and echos each element to the page.
在第8行,那有個陣列名為$yardlines。寫一個foreach遍歷整個陣列並在頁面echo取出的元素。

分享這篇文章:

發佈自 林品爵

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

關聯文章:

留下留言