Introduction to PHP

Loops (for / while)

A for loop repeats a fixed number of times for ($i = 1; $i <= 5; $i++). A while loop repeats as long as a condition stays true, which is useful when you don't know the exact count in advance.

Why this matters

  • ·Avoids repeating the same code manually many times
  • ·for loops are ideal when the number of repetitions is known

Common mistakes

  • ·Forgetting $i++ inside a while loop creates an infinite loop
  • ·Off-by-one mistakes (<= vs <) are one of the most common loop bugs
Your codePHP
Expected output
1 2 3 4 5

PHP runs on a server, not in the browser this shows the expected output instead of a live one.

Frequently asked questions

Use the code editor above edit the example freely and check the expected output against your own reasoning.

Practice questions

Question 1

Write a for loop that prints only the even numbers from 1 to 10.

Your codePHP
Expected output

PHP runs on a server, not in the browser this shows the expected output instead of a live one.

Quick check

Just for this topic answer honestly, then check yourself.

1 / 1

Which loop is best when you know exactly how many times to repeat?