首页 > 代码库 > Using loops for repetitive actions
Using loops for repetitive actions
Loops are an important labor-saving device commonly used in Programming Languages. When you need the same code repeated several times, typing it all out is tedious and time consuming. Instead, use a loop. The most basic type of loop is a while loop. It consists of the keyword, while, followed by a condition in parenthesis and the block of code in curly braces. As long as the condition remains true, the code inside the curly braces is repeated. The loop comes to an end when the condition is no longer true.
Here‘s a trivial example of a while loop. On this line, the variable I is set to 1. This is one of the rare occasions when it‘s acceptable to use a single letter as a variable name. By common convention, I is used as a counter in loops. If you need more than one counter, it‘s common to use j and k. The condition inside the parenthesis tells the loop to continue running while i is less than or equal to 10.
The code inside the curly braces displays i followed by an HTML br tag. And then on this line, I is incremented. So, let‘s see the result in a browser. It displays the numbers 1 to 10 with each number on a separate line. This is a deliberately simple example of a loop. The idea here is to show you the structure. Very often, you‘ll find that the code inside a loop is quite complex.
A variation of the while loop is the do while loop, in a do while loop, the condition comes after the block of code you want executed. So, you begin with the keyword do, a block of code in curly braces, and then while followed by the condition in parenthesis. It‘s also important to finish with a semicolon. The difference between these two loops is that the code in a do while loop will always be executed once, even if the condition is never true.
In this example, the code between the curly braces and the condition are exactly the same as in the while loop. The difference is that the counter has been initialized at 100. So, let‘s see what happens when we run that in a browser. And you can see that the counter is displayed once, and then nothing else happened. So, this line of code is executed. i is then incremented to 101, and then the condition is tested. And because I is greater than 10, the loop no longer runs. But if I go back to the while loop and change the counter to 100 here, Save and Refresh the page, just go back to that one, the loop doesn‘t run at all. So, that‘s the difference between a while loop and a do while loop. The danger with the while and do while whole loops is setting an impossible condition.
For example, if I reset the counter to 1 here and then comment out this line, in other words, I forget to increment the counter, each time that the loop runs, I will remain at 1. So, this condition will never be false and the loop will continue running until either the computer freezes or the browser crashes. So, this is the big danger, having a condition that will always be true, creating an infinite loop.
The for loop is less prone to generating an infinite loop. The basic syntax looks like this. The loop is controlled by three expressions separated by semicolons that go between the parentheses after the for keyword. The first expression is executed before the loop runs and is normally used to initialize a counter. The second expression sets the condition that determines how long the loop should run. And the third expression is executed at the end of each iteration of the loop, it‘s normally used to increment the counter.
It sounds complicated but it‘s quite simple in practice. Instead of displaying numbers, let‘s do something more practical. In this file, I‘ve created an array of characters from The Hitchhikers Guide To The Galaxy. The information is hardcoded here but it might come from an external source, such as a database. Let‘s use a for loop to display the character‘s names in an unordered list. So, I need to create a PHP block between these ul tags here, and a closing tag.
Then inside that PHP block, for. And then inside the parenthesis, I‘m going to initialize I to 0. That‘s because arrays are counted from 0 and I need a condition so it needs to be i is less than. There are 1, 2, 3, 4, 5 items in this array. Now, I could just simply hardcode 5 in there. But very often, you don‘t know what value you need, so instead, use count and put the name of the array inside the parenthesis, and this will give us the length of the array. And because we‘re counting from 0, the number of characters, the number of elements within the characters array, is the limit that we want to display. Now, a semicolon and we‘ll increase i.
There are the three expressions. And I see I‘ve got a syntax error there the reason for that is in sort of a curly brace, I‘ve got a square bracket there. There we go. Inside the curly braces we put the, the code. So it will be echo, and then we‘ll have a literal string for the li tag, the concatenation operator, and then, characters. And inside these square brackets in characters, I put the counter.
So, the first time that the loop runs, I will be 0, so it will display the first element in the array. The next time it runs, I will be 1, and so on. And then, the concatenation operator and the closing li tag. There we are. Let‘s just save that and view it in a browser.
What‘s happened is the four loop has gone through the elements in the array, and displayed them in an unordered list. Sometimes, it‘s useful to skip executing the code inside the loop and you do that by creating a conditional statement and using the continue keyword. So, if I create a conditional statement here, if I is equal 3, and then, a block of code there, continue.
So, what will happen is that if I is 3, it won‘t execute this line of code, so let‘s just see that refreshed in the browser. See, item 3 has disappeared. Of course, it‘s the fourth item in the array because arrays are counted from 0, as well as skipping an iteration of the loop. You very often need to stop the loop running all together and you do that using the break keyword. Let me just comment those lines out.
And what I want to do is I want to stop the loop running after Zaphod Beeblebrox. So, I‘m going to put a conditional statement in here. if characters I equals Zaphod Beeblebrox and then the block of code in curly braces, break. So, Save that and Refresh the browser.
What has happened now is that the loop has run, and as soon as it gets to characters equals Zaphod Beeblebrox, break stops the loop continuing from running. So, you never get as far as the remaining elements in the array. Of the three loops I‘ve shown you in this video, I think the for loop is the most useful. The do while loop is rather specialized because it always runs at least once even if the condition is never true. The while loop is elegantly simple, but is prone to creating an infinite loop if you‘re not careful.
You can skip an iteration of the loop using the continue keyword in a conditional statement and you can break out of a loop using break.
Using loops for repetitive actions