- Back to Home »
- PHP Tutorial »
- PHP For Loops
Posted by : senan
Wednesday, February 12, 2014
Welcome! In this section we going to cover the use of for loops in PHP.
For Loops
A for loop is used when we want to execute a block of code for certain number of times. For example, printing a value 5 times.
For Loop Syntax
for(initialize counter; condition until counter is reached; increment counter) { //execute block of code }
For loop has three statements.
- In the first statement, we initialize a counter variable to an number value.
- In the second statement, we set a condition (a max/min number value) until the counter is reached.
- In the third statement, we set a value by how much we want the counter variable to incremented by.
Lets look at an example to see how to create a for loop in PHP.
PHP For Loop
Example - Print number through 0 to 5 with PHP For Loop
<?php for($i=0; $i<=5; $i=$i+1) { echo $i." "; } ?>
In the above example, we set a counter variable $i to 0. In the second statement of our for loop, we set the condition value to our counter variable $i to 5, i.e. the loop will execute until $i reaches 5. In the third statement, we set $i to increment by 1.
The above code will output numbers through 0 to 5 as 0 1 2 3 4 5.
Note: The third increment statement can be set to increment by any number. In our above example, we can set $i to increment by 2, i.e., $i=$i+2. In this case the code will produce 0 2 4.
Example - Print number through 5 to 0 with PHP For Loop
What if we want to go backwards, that is, print number though 0 to 5 in reverse order? We simple initialize the counter variable $i to 5, set its condition to 0 and decrement $i by 1.
<?php for($i=5; $i>=0; $i=$i-1) { echo $i." "; } ?>
The above code will output number from 5 to 0 as 5 4 3 2 1 0 looping backwards.
Example - Print table with alternate colors using PHP For Loop
Let's have a look an interesting example of php for loop. You often seen tables cell with alternate colors on different websites. So, let say we want to print the numbers in a table with alternate colors. This is how we would do it.
0 |
1 |
2 |
3 |
4 |
5 |
<?php echo "<table width='100' align='center'>"; for($i=0; $i<=5; $i=$i+1) { if($i % 2 == 0) { echo "<tr>"; echo "<td style='background-color:red'>"; echo $i; echo "</td>"; echo "</tr>"; } else { echo "<tr>"; echo "<td style='background-color:green'>"; echo $i; echo "</td>"; echo "</tr>"; } } echo "</table>"; ?>
The above code sets different background color to the table cells depending on the value of $i. If $i is divisible by 2, which means if it is even then display color green, otherwise display color red.
Now that we are fimiliar with PHP for loop. Now, let's take a look at the last type of loop, the while loop in PHP.