PHP Tutorial



LOOPS IN PHP


🔁 PHP Loops

Loops are a fundamental part of programming, used to repeat a block of code a certain number of times or until a condition is met. In PHP, there are several types of loops available to make repetitive tasks more efficient.

💡 Tip: Loops help avoid repetitive code, making your scripts shorter and easier to maintain.

📝 Types of Loops in PHP

PHP provides four main types of loops:

  • for loop - Loops through a block of code a specified number of times.
  • while loop - Loops through a block of code as long as the specified condition is true.
  • do-while loop - Loops through a block of code at least once, then repeats the loop as long as the specified condition is true.
  • foreach loop - Loops through each element of an array.

1️⃣ The For Loop

The for loop is ideal when you know in advance how many times you want to loop through a block of code.

<?php
  for ($i = 0; $i < 5; $i++) {
      echo "Number: $i <br>";
  }
?>
  

In this example:

  • The loop starts with $i = 0 and continues as long as $i is less than 5.
  • After each iteration, the value of $i increases by 1.

2️⃣ The While Loop

The while loop repeats a block of code as long as a given condition is true.

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

Here:

  • The loop continues until $i is no longer less than 5.
  • Unlike the for loop, we manually increment $i inside the loop.

3️⃣ The Do-While Loop

The do-while loop is similar to the while loop, except it always runs the block of code once before checking the condition.

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

In this case:

  • Even if $i is initially greater than or equal to 5, the loop will run at least once.

4️⃣ The Foreach Loop

The foreach loop is specifically used for looping through arrays. It simplifies the process of accessing each array element.

<?php
  $colors = array("Red", "Green", "Blue");
  
  foreach ($colors as $color) {
      echo "Color: $color <br>";
  }
?>
  

In this example:

  • The foreach loop goes through each value in the $colors array and prints it.

✅ Key Takeaways:

  • For Loop is used when you know how many times you want to loop.
  • While Loop runs as long as the condition is true, but it doesn't know the number of iterations beforehand.
  • Do-While Loop ensures the code block is executed at least once.
  • Foreach Loop is perfect for arrays and automatically loops through all elements.

Using loops efficiently helps you avoid repetitive tasks and manage large datasets in PHP. 🎉


🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review