for and while Loops
Repeat code with for, while, and do-while loops.
Why Loops?
Loops let you repeat a block of code without copy-pasting it. PHP provides four looping constructs:
for— known iteration countwhile— condition-controlleddo-while— executes at least onceforeach— iterates arrays/objects (next lesson)
for Loop
The for loop has three parts: init, condition, increment:
<?php
for ($i = 0; $i < 5; $i++) {
echo $i . ' ';
}
// Output: 0 1 2 3 4All lessons in this course
- if, elseif, and else
- Switch and Match Statements
- for and while Loops
- foreach and Loop Control