The while loop method described in the previous article is very common. We can set a counter to start the loop. At the beginning of each iteration, the counter is tested in the conditional expression. At the end of the loop,
The while loop method described in the previous article is very common. We can set a counter to start the loop. At the beginning of each iteration, the counter is tested in the conditional expression. At the end of the loop, the counter content is modified. With the for loop, you can write a more concise and compact code to complete this loop operation. The basic structure of the for loop is:
For (expression 1, condition, expression 2) {Expression 3 ;}
Expression 1 is executed only once at the beginning. Generally, you can set the initial value of the counter here.
The conditional expression test will be tested before each loop starts. If the return value of the conditional expression is false, the loop ends. Generally, you can test whether the counter has reached the critical value.
Expression 2 is executed at the end of each loop. Generally, you can adjust the counter value here.
Expression 3 is executed once in every loop. Generally, this expression is a code block that contains a large number of circular code.
We can use the for loop to override the while loop statement in the previous article to implement the freight calculation instance. In this example, the PHP code can be changed:
For ($ distance = 50; $ distance <= 250; $ distance ++ = 50 ){
Ehco"
". $ Distance ."
". ($ Distance/10 )."
";}
?>
In terms of functions, the while version and for version are equivalent. The for loop is more compact, saving two lines of code. The two loops are equivalent-either better or worse. Under specific circumstances, you can select the loop statement to be used based on your preferences and feelings.
Note that we can combine variable variables and for loops to repeat a series of form fields. For example, if you have a form field named name1, name2, and name3, you can process it as shown in the following code:
For ($ I = 1; $ I <= $ numnames; $ I ++ ){
$ Temp = "$ name $ I ";
Echo $ temp .'
';
}
By dynamically creating variable names, you can access each form field in sequence. In addition to the for loop, PHP also provides the foreach loop statement, which is specially used for array usage. I will mention it in subsequent articles.