loops

Loops in PHP

Loops in PHP

Loops are used to execute a block of code repeatedly. PHP supports various types of loops.

For Loop

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 
"; } ?>

While Loop

The while loop runs as long as a condition is true:

      
        <?php
          $i = 1;
          while ($i <= 5) {
            echo "Number: $i 
"; $i++; } ?>

Activity

Try It Yourself!

Write a loop that prints all even numbers from 1 to 20.

Quiz

Quick Quiz

  1. When would you use a for loop instead of a while loop?
  2. What does the break statement do in a loop?

Answers: Use a for loop when you know the number of iterations beforehand; break stops the loop immediately.