Quick Reach
Introduction to While loop of PHP
The While loop is used to execute a block of code until the given condition is true. The condition check is similar to the one used in the PHP if statement to check if the condition is true or false.
See an example of while loop
In While PHP loop, after the code has been executed, the conditional statement will again be evaluated and the loop will continue until the given expression is found to be false.
The while loop Structure
Following is the general structure of PHP While loop:
while ( condition ){
//block of code here;
Increment;
}
Example of While loop
The following example shows using the While loop. The variable i is initiated with the value 0 and then incremented after executing statements by 1. The loop will go on until the value of i reaches 5.
Experience this example online
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
<?php
$i = 0;
while( $i < 5)
{
print $i."<br>";
$i++;
}
?>
|
While loop example with HTML
Following example uses the HTML table and fills with data based on While loop.
The output of the above code will be a table filled with Quantity and price as the while loops through the variable i.
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
28
29
30
31
|
<?php
$price = 5;
print "<table border="1" align="center">";
print "<tr><th>Quantity</th>";
print "<th>Price</th></tr>";
$i=10;
While ($i <= 100){
print "<tr><td>";
print $i;
print "</td><td>";
print $price * $i;
print "</td></tr>";
$i = $i + 10;
}
print "</table>";
?>
|
The PHP do while loop also works alike except the do while loop will execute the code at least once and then meet the condition. For more on do while and other loops visit the dedicated chapters by the links given below.
Other Loops: For Loop | Do While Loop | Foreach Loop
Leave A Comment?