PHP Loops
We are going to talk about all looping statements in PHP. We have four looping methods.
I. While loop
II. Do … While loop
III. For loop
IV. Foreach loop
Most of PHP statements are similar to C statements. So, a programmer who knows C, can learn PHP easily.
I. While Loop
While statement loops the operations while specified conditions are true. So, we can use this looping method when you don’t have or don’t know number of repetitions.
Structure 1.0 :
There is a simple code example that shows us how to use while loop in PHP.
Example 1.0 :
Output of Example 1.0 :
II. Do … While Loop
With do…while loop, conditions are tested at the end of the loop. The loop is always executed at least once with this usage.
Structure 2.0:
Example 2.0 :
Output of Example 2.0 :
III. For Loop
The for loop depends on a counter ( that increases or decreases by the same amount each time through the loop ) and loops the operations until the counter reaches a specified value.
Structure 3.0:
Example 3.0:
Output of Example 3.0:
IV. Foreach Loop
For each … next statement is used for executing a block of operations for each element of a collection. There is no counter in for each … next loop but you have to declare an object variable.
Structure 4.0:
Example 4.0:
Output of Example 4.0:
V. Break and Continue Statements in PHP Loops
5.1 ) Break Statement
Break statement is used for exiting from the loop that contains the break statement immediately.
Example 5.0
Output of Example 5.0:
Example 5.1
Output of Example 5.1:
As you see in the Example 5.0 and Example 5.1 the loop is broken when the break statement is read.
5.2 ) Continue Statement
Continue statement is used for skipping from the loop that contains the continue statement immediately..
Example 5.2
Output of Example 5.2:
In the example 5.2, when i reaches 7, operation is skipped and 7 is not written.

Recently Typed