PHP Loops
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.
For Loop
The for loop repeats a block of code a specific number of times:
<?php
for ($i = 0; $i < 5; $i++) {
echo "Number: $i <br>";
}
?>
While Loop
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++;
}
?>
Activity
Try It Yourself!
Write a loop that prints the first 10 even numbers.
Quiz
Quick Quiz
- What is the purpose of a loop in PHP?
- How do you write a
whileloop in PHP?
Answers: A loop repeats a block of code multiple times. You write a while loop by defining a condition at the start.