Repetitive structures (WHILE, FOR, FOREACH, DO WHILE)

Iterative loops are designed to repeat a task as long as a condition is met or until the loop is explicitly chosen to exit..

WHILE

Example
Output
Number 1
Number 2
Number 3

FOR

Example
FOR can also be used successfully if we have several variables that have successively incremented numerical suffixes; for example, if we have $variab1, $variab2, $variab3, etc., ${"variab$i"} can be used.
The output will be:

FOREACH

Example

DO WHILE

Example
The output is the same in all three cases:

Use of consecutively numbered items

In order to make it convenient to use FOR, when we use elements that are numbered (as we have exemplified above), the root of that element can be extracted and concatenated with $i.
So for $img1, $img2... we use ${"img$i"}.

If we look in the page source, we will see as follows:

One way to set the maximum that the counter variable, $i, can have is by using an array. Thus, instead of:

we will have:

Break/Continue

Break can be used to exit a loop.. Continue breaks an iteration when a condition occurs and continues with the next iteration in the loop..

Break

Example

Output
Number 1
Number 2
Number 3

Continue

Example

Output
Number 1
Number 2
Number 4
Number 5


  1. Meloni, J., Învaţă singur, PHP, MySQL şi Apache. Toate într-o singură carte, Ed. Corint, Bucureşti, 2005, p. 100.
  2. W3Schools.com

Author: Ovidiu.S

I am quite passionate about this professional area as if I know something - no matter how little - I want to share it with others.

Leave a Reply