💡 Ask Tutor

Loops in PHP – Repeating Code Efficiently

What Are Loops in PHP?

Loops allow you to execute a block of code repeatedly, either a set number of times or while a certain condition is true.

They are essential in many real-world scenarios:

  • Displaying a list of items from a database
  • Processing form inputs
  • Automating repetitive tasks (e.g., sending emails)
  • Creating dynamic tables, charts, and HTML elements

The while Loop

The while loop runs as long as a specified condition is true.

Syntax:

PHP
while (condition) {
  // code to execute
}

Example:

PHP
<?php
$count = 1;

while ($count <= 5) {
  echo "Number: $count<br>";
  $count++;
}
?>

Output:

YAML
Number: 1  
Number: 2  
Number: 3  
Number: 4  
Number: 5

Great for situations where you don’t know in advance how many times the loop should run.

The do...while Loop

This loop will always run at least once, even if the condition is false.

Syntax:

PHP
do {
  // code to execute
} while (condition);

Example:

PHP
<?php
$attempt = 1;

do {
  echo "Login attempt $attempt<br>";
  $attempt++;
} while ($attempt <= 3);
?>

Output:

Bash
Login attempt 1  
Login attempt 2  
Login attempt 3

Useful for input prompts or retry operations where the action must occur before checking a condition.

The for Loop

The for loop is ideal when the number of repetitions is known.

Syntax:

PHP
for (initialization; condition; increment) {
  // code to execute
}

Example:

PHP
<?php
for ($i = 1; $i <= 10; $i++) {
  echo "Row $i<br>";
}
?>

Output:

Bash
Row 1  
Row 2  
...
Row 10

Excellent for working with numeric ranges or indexed loops.

The foreach Loop

foreach is used specifically for arrays. It loops through each item in the array automatically.

Syntax:

PHP
foreach ($array as $value) {
  // code using $value
}

Example:

PHP
<?php
$colors = ["Red", "Green", "Blue"];

foreach ($colors as $color) {
  echo "Color: $color<br>";
}
?>

Output:

LESS
Color: Red  
Color: Green  
Color: Blue

You can also get both key and value:

PHP
foreach ($colors as $index => $color) {
  echo "Index $index: $color<br>";
}

Using break and continue

  • break: Exits the loop completely
  • continue: Skips the current iteration and continues with the next one

Example: break

PHP
<?php
for ($i = 1; $i <= 10; $i++) {
  if ($i == 5) break;
  echo "$i<br>";
}
?>

Output:

1  
2  
3  
4

Example: continue

PHP
<?php
for ($i = 1; $i <= 5; $i++) {
  if ($i == 3) continue;
  echo "$i<br>";
}
?>

Output:

1  
2  
4  
5

Real-World Loop Examples

Example: Generate a Dropdown with Years

PHP
<?php
echo "<select>";
for ($year = 2000; $year <= 2025; $year++) {
  echo "<option>$year</option>";
}
echo "</select>";
?>

Example: Sum All Even Numbers from 1 to 50

PHP
<?php
$sum = 0;

for ($i = 1; $i <= 50; $i++) {
  if ($i % 2 == 0) {
    $sum += $i;
  }
}
echo "Total: $sum";
?>

Best Practices

  • Initialize loop variables properly
  • Avoid infinite loops — always ensure the condition will eventually be false
  • Use foreach for arrays instead of for with indexes
  • Keep loops efficient and avoid heavy computations inside them
  • Minimize nesting (loop within loop) where possible

Common Mistakes to Avoid

  • Forgetting to increment in while or for loop
  • Using the wrong loop type for the task (e.g., for instead of foreach)
  • Accidentally creating infinite loops
  • Not resetting counters properly

Notes:

  • Use while when the number of iterations is unknown
  • Use do...while to ensure at least one execution
  • Use for when the number of iterations is fixed
  • Use foreach to loop through arrays efficiently
  • Use break to exit early and continue to skip an iteration

Practice Tasks

Task 1: Count Multiples of 5
Loop from 1 to 100 and print all numbers that are divisible by 5.

Task 2: Loop Through an Array
Create an array of your favorite programming languages and print each using foreach.

Task 3: Star Pattern Generator
Use nested for loops to create this:

Markdown
*
**
***
****
*****