Php 7 For Loop Foreach Loop Simple Explanations

Subscribe

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

Php 7 For Loop Foreach Loop Simple Explanations was last modified: October 29th, 2021 by Maximus Mccullough

Php 7 For Loop Foreach Loop Simple Explanations

Pages: 1 2 Next

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.