3.2 Iterating Loops
3.2 Iterating Loops
Iterating / Loops
Often when you write code, you want the same block of code to run
over and over again in a row. Instead of adding several almost equal code-lines
in a script, we can use loops to perform a task like this.
In PHP, we have the following looping statements:
Syntax
Example:
<?php
$x = 1;
while($x <= 5) {
echo "The number is: $x <br>";
$x++;
}
?>
The PHP do...while Loop
Example:
<?php
$x = 1;
do {
echo "The number is: $x <br>";
$x++;
} while ($x <= 5);
?>
The PHP for Loop
Parameters:
Example
<?php
for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x <br>";
}
?>
The PHP foreach Loop
Example
<?php
$array = array( 1, 2, 3, 4, 5);
foreach( $array as $x )
{
echo "The number is $x <br />"; }
?>