FOR loop

The for syntax in PHP is exactly the same as that in html. Just like in html, you define a variable, followed by the codition, followed by the increment (what happens to the variable after each iteration). For example:

for ($i = 20; $i >= 0; $i = $i - 2 ){
echo ($i."<br>");
}


20
18
16
14
12
10
8
6
4
2
0

Common use of FOR loop

As the example below demonstrates, the for loop is most commonly used for displaying the content of an array.

$fruits = array("Apples", "Oranges", "Grapes", "Banana", "Peaches");
for ($i=0; $i < sizeof($fruits); $i++){
echo ($fruits[$i]."<br>");
};


Apples
Oranges
Grapes
Banana
Peaches

FOREACH loop

The foreach loop simplifies a loop that is being used to process an array.

foreach ($fruits as $key => $value){
echo ("Index = ".$key.", value = ".$value."<br>); };


Index = 0, value = Apples
Index = 1, value = Oranges
Index = 2, value = Grapes
Index = 3, value = Banana
Index = 4, value = Peaches

It is also possible to easily update the value of the array inside foreach loop:

foreach ($fruits as $key => $value){
echo ("Index = ".$key.", value = ".$value."<br>); };


Before upate... Index = 0, value = Apples
After update... Value = Yummy Apples

Before upate... Index = 1, value = Oranges
After update... Value = Yummy Oranges

Before upate... Index = 2, value = Grapes
After update... Value = Yummy Grapes

Before upate... Index = 3, value = Banana
After update... Value = Yummy Banana

Before upate... Index = 4, value = Peaches
After update... Value = Yummy Peaches

Here is an example of a nested foreach loop:

$students = array("Pavan", "Lori", "Anthony", "Ethan", "Asha");
$pavanGrades = array(83, 77.70, 78, 91, 94);
$loriGrades = array(89, 97.70, 73, 81, 89);
$ethanGrades = array(89, 92, 88, 96, 94);
$anthonyGrades = array(89, 87, 88, 86, 84);
$ashaGrades = array(87, 74.70, 92, 89, 93);
$studentGrade = "";
$gradeFlag = false;

echo ("<h1>INTEGRATED MATH</h1>");
echo ("</h6> The following students scored 90 or higher in their summative tests over the semester:</h6>");

foreach ($students as $key => $value){

$studentGrade = strtolower($value)."Grades";

echo ("<br><br>".$value." scored a 90 or higher in the following summative tests:<br1>");

$gradeFlag = false;
foreach ($$studentGrade as $key2 => $value2){

if ($value2 >= 90){

$gradeFlag = true;
echo ($value2."<br>>");

};

};

//If student did not score over 90 in any grade
if ($gradeFlag == false){
echo("None <br>");
};

};


INTEGRATED MATH

The following students scored 90 or higher in their summative tests over the semester:


Pavan scored a 90 or higher in the following summative tests:
91
94


Lori scored a 90 or higher in the following summative tests:
97.7


Anthony scored a 90 or higher in the following summative tests:
None


Ethan scored a 90 or higher in the following summative tests:
92
96
94


Asha scored a 90 or higher in the following summative tests:
92
93