Guide to PHP and MySQL (University at Buffalo Version)
Chapter 5: Using PHP Loops
PHP provides a few different control structures that allow you to loop through data using a set of statements.
The PHP for
Loop
The for
statement provides a way to loop through a statement, or group of statements, a number of times.
for ($i = 0; $i 5; $i++) {
print("\$i = $i<br/>\n");
}
?>
for
Loop$i = 1
$i = 2
$i = 3
$i = 4
for
Loop OutputThe PHP foreach
Loop
The foreach
loop statement provides a way to "walk" through an associative array.
$statesArray = array("AK" => "Alaska", "AL" => "Alabama", "AR" => "Arkansas", "AZ" => "Arizona");
foreach ($statesArray as $state => $stateValue) {
print("Array element $state = $stateValue<br/>\n");
}
?>
foreach
LoopArray element AL = Alabama
Array element AR = Arkansas
Array element AZ = Arizona
foreach
Loop OutuputThe PHP while
Loop
The while
loop statement provides a way to to perform a statement or statements based on a condition being true or false.
$counter = 0;
$maxNum = 3;
/* Loop until $counter is greater than $maxNum */
while ($counter < $maxNum) {
echo("counter = " . $counter++ . " & maxNum = $maxNum<br/>\n");
}
?>
while
Loopcounter = 1 & maxNum = 3
counter = 2 & maxNum = 3
while
Loop OutputThe PHP do / while
Loop
The do ... while
loop statements provide a way to to perform a statement or statements based on a condition being true or false. A do ... while
loop tests the condition at the end of the loop. So, a do ... while
loop will always execute at least once.
$counter = 4;
$maxNum = 3;
/* Loop until $counter is greater than $maxNum */
do {
echo("counter = " . $counter++ . " & maxNum = $maxNum<br/>\n");
} while ($counter < $maxNum);
?>
do / while
Loopdo ... while
Loop Output