PHP PHP Tutorial PHP Forms PHP Advanced PHP OOP PHP MySQL Database PHP XML PHP - AJAX



PHP Loops

PHP loops are used to execute a block of code repeatedly based on a condition. Loops are an essential part of any programming language, and PHP provides several types of loops to choose from.

Types of Loops in PHP

PHP provides four types of loops:

  • while loop
  • do-while loop
  • for loop
  • foreach loop

While Loop

The while loop executes a block of code as long as the specified condition is true. The syntax for the while loop is:


while (condition) {
  // code to be executed
}

Here is an example of a while loop that prints the numbers 1 to 5:


$i = 1;
while ($i <= 5) {
  echo $i . "<br>";
  $i++;
}

The output of this code will be:


1
2
3
4
5

Do-While Loop

The do-while loop is similar to the while loop, but the block of code is executed at least once, even if the condition is false. The syntax for the do-while loop is:


do {
  // code to be executed
} while (condition);

Here is an example of a do-while loop that prints the numbers 1 to 5:


$i = 1;
do {
  echo $i . "<br>";
  $i++;
} while ($i <= 5);

The output of this code will be:


1
2
3
4
5

For Loop

The for loop is used when you know how many times you want to execute a block of code. The syntax for the for loop is:


for (initialization; condition; increment) {
  // code to be executed
}

Here is an example of a for loop that prints the numbers 1 to 5:


for ($i = 1; $i <= 5; $i++) {
  echo $i . "<br>";
}

The output of this code will be:


1
2
3
4
5

Foreach Loop

The foreach loop is used to iterate over arrays. The syntax for the foreach loop is:


foreach ($array as $value) {
  // code to be executed
}

Here is an example of a foreach loop that prints the values of an array:


$colors = array("red", "green", "blue");
foreach ($colors as $color) {
  echo $color . "<br>";
}

The output of this code will be:


red
green
blue

Conclusion

Loops are an essential part of any programming language, and PHP provides several types of loops to choose from. Whether you need to iterate over an array or execute a block of code a certain number of times, PHP has a loop that will meet your needs.

References

Activity