For Loop
Used when you know in advance how many times you want to execute a statement or a block of
statements.
for($x = 0; $x <= 5; $x++) { echo "The number is: $x"; }
While Loop
It executes a block of code as long as the specified condition is true.
$x = 1; while($x <= 5) { echo "The number is: $x "; $x++; }
Do…While Loop
$x = 1; do { echo "The number is: $x "; $x++; } while ($x <= 5);
Foreach Loop
Used for looping through arrays. For each loop iteration, the value of the current array element is
assigned to the value variable and the array pointer is moved by one, until it reaches the last array
element.
$colors = array("red", "green", "blue", "yellow"); foreach ($colors as $value) { echo "$value"; }
$age = array("Peter" => "35", "Ben" => "37", "Joe" => "43"); foreach($age as $key => $value) { echo "$key is $value years old. "; }