Quick Reach
The for loop in PHP
Loops are the way to execute specified block of code again and again to a given number of times. There will be many scenarios in programming life when you need one or the other type of loop in order to achieve a task.
See an example of for loop
Types of loops in PHP
Four types of loops are supported in PHP:
- The for loop
- while loop
- do…while loop
- foreach – loop
This chapter will discuss PHP For loop only. The for loop, also known as iteration statement is generally used when you know the number of iterations in loops.
Structure of for loop
Following is the general structure of PHP for loop:
for ( initialization; condition; increment the counter){
Code to be executed;
}
- The first parameter in for loop PHP sets a counter initial value.
- The second parameter tells until when code should be executed.
- The Third parameter increments/decrements a counter.
- Execute the code within the for loop enclosed in curly braces.
Example of for loop in PHP
In the following example, a variable i is initialized with a value of 0. The loop iterates through until the value of the variable i reaches 5. In each iteration, the variable will be incremented by 1.
In the curly braces, we used a print statement to display the current value of i. See the example by clicking the link below or copy/paste the code in your editor:
Experience this example online
1
2
3
4
5
6
7
8
9
10
11
12
13
|
<?php
//Example of For loop to print value of I starting from 0, till it reaches 4
for( $i=0; $i<5; $i++ )
{
Print $i.“<br>”;
}
?>
|
For loop – more real example
Following example mixes HTML with for loop to generate HTML table as the output with Quantity and price headers.
Experience this example online
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
<?php
$price = 5;
print “<table border=”1″ align=”center”>”;
print “<tr><th>Quantity</th>”;
print “<th>Price</th></tr>”;
for ( $i = 10; $i <= 100; $i += 10) {
print “<tr><td>”;
print $i;
print “</td><td>”;
print $price * $i;
print “</td></tr>”;
}
print “</table>”;
?>
|
Following are the links to other loop types in PHP.
While Loop | Do While Loop | Foreach Loop
Leave A Comment?