PHP for loop tutorial
In this tutorial I will show you with a lot of code example how to use the for loop in PHP.
Tutorial info:
Name: | PHP for loop tutorial |
Total steps: | 2 |
Category: | Basics |
Level: | Beginner |
Bookmark PHP for loop tutorial

Step 1 - For loop basics
PHP for loop tutorial
The for loop is the most used and the most complex loop. However it's usage is not so complicated. The definition of the for statement looks like this:
for (expr1; expr2; expr3) statement
As you can see with 3 expressions it is really more complex than a while loop.
What does these expressions means? Let's discuss it one-by-one.
- expr1: This expression is called only once and this is the first statement which is executed during the loop lifetime. In general loop variable initialization used to be here.
- expr2: This condition is checked in each iteration. If it is true then the statement will be executed.
- expr3: As final step of each iteration this code will be executed.
As you can see here we first initialised the $i variable with 0. Afterwards we defined a condition which is true until the value of $i is less than 10. As last step we increment the value of the variable to avoid endless loop. As result the echo statement will be executed 10 times printing out its actual value.
As usual you can use code blocks instead of only one statement. However in case of only one statement I recommend to use code blocks between {} as it can eliminate some further problem.
Of course you can change the value of the loop variable inside the loop, but be careful with this solution.
Next Step of PHP for loop tutorial
Tags: php for loop, for loop, php for, php, for, loop
PHP for loop tutorial - Table of contents |
---|
Step 1 - For loop basics |
Step 2 - Break and continue the for loop |