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>");
}
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>");
};
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>);
};
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>);
};
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>");
};
};