PHP Loops

PHP Loops

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.


The while Loop

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

While Example

<?php
$x = 1;

while($x <= 5) { echo "The number is: $x <br>"; $x++; } ?>

The for Loop

The for loop is used when you know in advance how many times the script should run.

The foreach Loop

The 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>"; } ?>