Both the "while" and "do-while" loops continue to iterate for so long as the specified conditional expression remains true. But there often arises a need to execute a certain set of statements a specific number of times - for example, printing a series of thirteen sequential numbers, or repeating a particular set of <TD>> cells five times. In such cases, clever programmers reach for the "for" loop... The "for" loop typically looks like this:
Looks like gibberish? Well, hang in there for a minute...the "counter" here is a PHP variable that is initialized to a numeric value, and keeps track of the number of times the loop is executed. Before each execution of the loop, the "condition" is tested - if it evaluates to true, the loop will execute once more and the counter will be appropriately incremented; if it evaluates to false, the loop will be broken and the lines following it will be executed instead. And here's a simple example that demonstrates how this loop can be used: Let's dissect this a little bit: The first thing we've done here is define the number to be used for the multiplication table; we've used 7, since we're particularly poor at math - you might prefer to use another number. Next we've constructed a "for" loop with $x as the counter variable - we've initialized it to 1 and specified that the loop should run no more than 15 times. The $x++ you see in the "for" statement is an interesting little operator known as the auto-increment operator - more on this in the "Miscellaneous Notes" section below. For the moment, all you need to know is that it automatically increments the counter by 1 every time the loop is executed. Finally, the line that does all the work - the "echo" statement, which takes the number specified, multiplies it by the current value of the counter, and displays the result on the page. As you can see, a "for" loop is a very interesting - and useful - programming construct. Our next example illustrates its usefulness in a manner that should endear it to any HTML programmer. And here's the output: As you'll see if you try coding the same thing by hand, PHP's "for" loop just saved you a whole lot of work!
blog comments powered by Disqus |