w1coding.comAll tutorials

PHP Loops

PHP lessons
  1. Environment Setup
  2. Introduction
  3. Variables
  4. Basics
  5. Operators
  6. Control
  7. Loops
  8. Variables
  9. Functions
  10. Arrays
  11. Superglobal
  12. File
  13. Loops
  14. Date
  15. Loops
  16. Strings
  17. Error
  18. Class
  19. File
  20. Include
  21. Sessions
  22. Mysql
  23. Cookies
  24. Forms
  25. Cookies
  26. Regular
  27. Authenthication
  28. Fileupload
  29. Mvc
  30. Responsive

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

  1. What is the purpose of a loop in PHP?
  2. How do you write a 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.