Often when you write code, you want the same block of code to run over and over again a certain number of times. So, instead of adding several almost equal code-lines, we can use loops.
PHP supports four types of loops: while, do...while, for, and foreach.
while LoopThe while loop executes a block of code as long as the specified condition is true.
<?php $x = 1;while($x <= 5) { echo "The number is: $x <br>"; $x++; } ?>
for LoopThe for loop is used when you know in advance how many times the script should run.
foreach LoopThe foreach loop works only on arrays, and is used to loop through each key/value pair in an array. This is by far the most commonly used loop in web development when handling database results!
<?php
$colors = array("red", "green", "blue", "yellow");
foreach ($colors as $value) {
echo "$value <br>";
}
?>