Loops are the final type of control structure discussed in this chapter. As suggested earlier, you use loops to execute a section of code repeatedly. You may want to create a drop-down menu consisting of the days of the month (print the numbers 1 through 31). Or you may want to print out each value of an array. For either of these cases, and many more, you can use a loop. (Note: The latter example is demonstrated in Chapter 7, Using Arrays.)
PHP supports three kinds of loops: for, while, and foreach. The while loop is similar to for, but it is used most frequently when retrieving values from a database. Foreach is related to using arrays and is introduced in Chapter 7.
The for loop is designed to perform specific statements for a determined number of iterations (unlike while, which runs until the condition is FALSE—so they are similar, but significantly different.). You normally use a dummy variable in the loop for this purpose:
The initial expression is executed once, the first time the loop is called. Then the condition is used to determine whether to execute the statements. The closing expression is executed each time the condition is found to be TRUE, but only after the statements are executed.
This may make more sense when viewing a sample for loop, as it would be syntactically executed. Here is a simple loop that prints out the numbers 1 through 10:
And rewritten as follows (assuming PHP had a GOTO method), this may further illustrate the concept to you:
This exercise will give you some practice with the for loop. You will use it to create the day drop-down menu in the HTML form.
Links
[1] https://www.studyanywhere.ca/advanced-courses/intro-php/chapter-6/control-structures/exercise-7
[2] https://www.studyanywhere.ca/advanced-courses/intro-php/chapter-6/control-structures/exercise-7#open_here
[3] https://www.studyanywhere.ca/advanced-courses/intro-php/chapter-6/control-structures/exercise-7#open_here2
[4] https://www.studyanywhere.ca/advanced-courses/intro-php/chapter-1/getting-started-with-php/exercise-1#anchor
[5] https://www.studyanywhere.ca/advanced-courses/intro-php/chapter-6/control-structures