PHP for loop tutorial

Home - Tutorials - Basics

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

Bookmark PHP for loop tutorial

Bookmark and Share

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.

Let's see a real example how it looks like:
  1. for ($i=0;$i<10;$i++) echo "$i<br/>";
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.
  1. for ($i=0;$i<10;$i++) {
  2. echo "$i<br/>";
  3. echo "-------<br/>";
  4. }

Of course you can change the value of the loop variable inside the loop, but be careful with this solution.
  1. for ($i=0;$i<10;$i++) {
  2. echo "$i<br/>";
  3. echo "-------<br/>";
  4. $i++;
  5. }

Next Step of PHP for loop tutorial

Tags: php for loop, for loop, php for, php, for, loop

Follow phpf1 on Twitter

F1 Site Family
Database F1
Java F1
JavaScript F1

Total time: 0.0355