Loops in PHP are used to execute a block of code multiple times. There are different types of loops like for
, while
, foreach
, and do-while
.
The for
loop repeats a block of code a specific number of times:
<?php
for ($i = 0; $i < 5; $i++) {
echo "Number: $i <br>";
}
?>
The while
loop repeats a block of code as long as a condition is true:
<?php
$i = 0;
while ($i < 5) {
echo "Number: $i <br>";
$i++;
}
?>
Write a loop that prints the first 10 even numbers.
while
loop in PHP?Answers: A loop repeats a block of code multiple times. You write a while
loop by defining a condition at the start.