Tt
Click this widget to change the font size.
CC
Click this widget to change contrast.

Home Page 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | Links | Search | Bio |

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.

<?php
for ($i = 0; $i 5; $i++) {
  print("\$i = $i<br/>\n");
}
?>

Figure 5-1: A PHP for Loop
$i = 0
$i = 1
$i = 2
$i = 3
$i = 4


Figure 5-2: PHP for Loop Output

The PHP foreach Loop

The foreach loop statement provides a way to "walk" through an associative array.

<?php
$statesArray = array("AK" => "Alaska", "AL" => "Alabama", "AR" => "Arkansas", "AZ" => "Arizona");
foreach ($statesArray as $state => $stateValue) {
  print("Array element $state = $stateValue<br/>\n");
}
?>

Figure 5-3: PHP foreach Loop
Array element AK = Alaska
Array element AL = Alabama
Array element AR = Arkansas
Array element AZ = Arizona


Figure 5-4: PHP foreach Loop Outuput

The 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.

<?php
$counter = 0;
$maxNum = 3;
/* Loop until $counter is greater than $maxNum */
while ($counter < $maxNum) {
  echo("counter = " . $counter++ . " & maxNum = $maxNum<br/>\n");
}
?>

Figure 5-5: PHP while Loop
counter = 0 & maxNum = 3
counter = 1 & maxNum = 3
counter = 2 & maxNum = 3


Figure 5-6: PHP while Loop Output

The 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.

<?php
$counter = 4;
$maxNum = 3;
/* Loop until $counter is greater than $maxNum */
do {
  echo("counter = " . $counter++ . " & maxNum = $maxNum<br/>\n");
} while ($counter < $maxNum);
?>

Figure 5-7: PHP do / while Loop
counter = 4 & maxNum = 3


Figure 5-8: PHP do ... while Loop Output
Let's Get Started with a PHP for Loop Page!
Let's Get Started with a PHP while Loop Page!

Help contribute to my OER Resources. Donate with PayPal button via my PayPal account.
Creative Commons License This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License. Copyright © 2016-2024 Jim Gerland