For Loop

PHP for loops are a complicated concept. It is a combination of a statement, a condition, and another statement. Basically, a loop is a repeating if statement. Let’s just go ahead and jump into an example.


for($i = 0; $i < 5; $i++) //statement 1 var $i = 0; condition $i<5; statement2 $i++;

echo $i; //write current value of variable $i
echo ‘<br/>’;

echo ” End of for loop “;


End of for loop

The for loop is somewhat like a modified if statement that restarts itself until the condition is satisfied. Inside of the for loop, we have the statement $i = 0;
that declares a variable $i and sets it equal to 0. Next, we have the conditional $i < 5 that is the if part of the statement. We know that the conditional says if $i < 5, then run the statements in the { }. Finally, we have an increment operator statement, $i++, which is the most commonly used way to advance a for loop. Since the ++ is after the variable, we will increment i after all of the statements in the { } have been executed. This is exactly why when we echo $i for the first time it is 0 rather than 1. So, we run through the statements in the { } and we get the results 0,1,2,3,4. Right after the final execution of statements, $i is incremented to 5, which was then compared against the conditional $i < 5. It is obviously false at this stage; therefore, we move outside of the for loop and we execute the next line of code that happens to be our echo ” End of for loop “; statement.

PHP For Loop iteration

In the image above, we can see how PHP runs through a for loop. Every time all of the code has been executed in the parentheses, PHP goes back up and checks the condition in the for loop. If the condition is still true, PHP executes the code in the parentheses again until the condition is no longer true.

If you enjoyed this resource, support me by sharing this page with others.
Share on Facebook
Share on Google+
Share on StumbleUpon
Digg this
Tweet about this on Twitter
Share on Reddit

Leave a Comment

  1. Just finished reading the first example, and I corrected the mistake in line 5 to get it right. Line 5 is missing "$" sign before variable i.

Leave a Reply

Your email address will not be published. Required fields are marked *