Loops are used to execute a block of code repeatedly. PHP supports various types of loops.
The for
loop is used when you know how many times the loop should run:
<?php
for ($i = 1; $i <= 5; $i++) {
echo "Number: $i
";
}
?>
The while
loop runs as long as a condition is true:
<?php
$i = 1;
while ($i <= 5) {
echo "Number: $i
";
$i++;
}
?>
Write a loop that prints all even numbers from 1 to 20.
for
loop instead of a while
loop?break
statement do in a loop?Answers: Use a for
loop when you know the number of iterations beforehand; break
stops the loop immediately.