Tip:
Highlight text to annotate it
X
The loop statements are used to execute a specific block several times. There are four
loops in PHP: while, do while, for, and foreach.
The while loop runs through the code block only if condition is true and will continue
looping for as long as the condition remains true. Note that the condition is only checked
at the beginning of each iteration. This loop here will echo the numbers 0 to 9. As with
the conditional statements the braces in the while loop can be rewritten into a colon and
the endwhile keyword.
Next, there's the do while loop that works the same as the while loop, except that it
checks the condition after the code block and will therefore always runs through the
code block at least once.
The for loop is used to go through a code block a specific number of times. It takes
three parameters. The first parameters initializes a counter and is always executed once. The
second parameter holds the condition for the loop and is checked before the beginning of
each iteration. The third parameter contains the increment to the counter and is executed
at the end of the iteration after the code block. The braces can be rewritten here as
well, with a colon and the endfor keyword. The for loop has several variations since
either one of the parameters can be left out. For example, if we leave out the first and
third parameter it functions the same as the while loop. The first and third parameters
can also be split into several statements with the comma operator (,).
Finally, the foreach statement gives an easy way to loop through arrays. On each loop,
the value of the current element in the array is assigned to the value variable and the
loop continues to execute until it has gone through the entire array. It will here print
the numbers 1, 2, and 3. If the array has both keys and values there is an extension
of the foreach loop to also gets the key name, by adding a key variable with the arrow operator.
These are the four loops on PHP. As with the if statement the braces can be left out completely
if there's only one statement in the code block.
Another important keyword is the break keyword that ends execution of the current for, while,
or switch statement. It can be given a numeric argument to break out of more than one nested
statement. In this case to end both loops. There is also the continue keyword that can
be used within any looping statement to skip the rest of the current loop and continue
at the beginning of the next iteration. In this case it would produce an endless loop
since the for loop has no counter or condition. This keyword as well can accept an argument
for how many enclosing loops it should skip to the end of.