“Php 7 for loop” and “foreach loops” will display a block of code for a number of times. We initialize the for loop with a parameter unlike what we did in the while loops. Next, we set the comparison operator and finally we increment the number of times the loop should run. Here are the files for this lesson.
Php 7 For Loop
Here is an example of a Php 7 for loop. What we want to do it repeat the numbers until it reaches the number 5 and then stop. Set the parameters to start out at zero then set our comparison operator to see if the number is less than or equal to 5. Finally, increment the number so it adds on 1.
for($var=0; $var <= 5; $var++){ echo "<p>$var </p>"; }
In the last lesson we showed examples on how this can be done with the “while loop” and “do while loop“.
Php 7 Foreach Loop
The Php 7 foreach loop is reserved for arrays and objects. First set the array then begin the foreach loop. In the parameters for the foreach loop you need to change the name of the variable. Use the “as” in the statement Here is an example of a foreach loop.
$var=array("pizza", "ice cream","salad","hamburgers"); foreach($var as $newvar){ echo "<p> I ate $newvar</p>"; }
Next we will discuss foreach loops in an object.
A1WEBSITEPRO Social Media Pages
Here are my social media pages, lets hook up!