A loop repeats a block of code several times without rewriting it. It is essential for going through a list or counting.
The for loop
Ideal when you know how many repetitions you need. It has three parts: an initialisation, a condition and an increment.
- for ($i = 1; $i <= 5; $i++) repeats 5 times.
- $i++ increases $i by 1 on each pass.
The while loop
Ideal when you do not know the number of passes in advance: it keeps going as long as the condition stays true.
- The condition is checked.
- If it is true, the block runs.
- It starts again until the condition becomes false.
Careful: always make sure the condition can change, otherwise the loop runs forever and freezes the script!
Key point: use for when you know the number of passes, and while when you loop « as long as » a condition is true.