Saturday, 15 December 2012

PHP While Loop

While loop in PHP

While loops are the simplest type of loop in PHP. They behave just like their Java and C Language counterparts. The basic form of a while statement is:

while (expr)
statement

The meaning of a while statement is simple. It tells PHP to execute the nested statement(s) repeatedly, as long as the while expression evaluates to TRUE. The value of the expression is checked each time at the beginning of the loop, so even if this value changes during the execution of the nested statement(s), execution will not stop until the end of the iteration (each time PHP runs the statements in the loop is one iteration).

Sometimes, if the while expression evaluates to FALSE from the very beginning, the nested statement(s) won't even be run once. Like with the if statement, you can group multiple statements within the same while loop by surrounding a group of statements with curly braces, or by using the alternate syntax:

while (expr):
statement
...
endwhile;

Example:
$article_price = 5;
$quantity = 10;

echo "<table border=\"1\" align=\"center\">";
echo "<tr><th>Quantity</th>";
echo "<th>Article Price</th></tr>";
while ( $counter <= 100 ) {
        echo "<tr><td>";
        echo $counter;
        echo "</td><td>";
        echo $brush_price * $counter;
        echo "</td></tr>";
        $counter = $counter + 10;
}
echo "</table>";

do-While

do-while loops are very similar to while loops, except the truth expression is checked at the end of each iteration instead of in the beginning. The main difference from regular while loops is that the first iteration of a do-while loop is guaranteed to run (the truth expression is only checked at the end of the iteration), whereas it's may not necessarily run with a regular while loop (the truth expression is checked at the beginning of each iteration, if it evaluates to FALSE right from the beginning, the loop execution would end immediately). We given below a Simple program that explain clearly do-while loop.

<html>
<body> 
<?php
$i=1;
do
  {
  $i++;
  echo "The value is " . $i . "<br />";
  }
while ($i<=10);
?>

0 comments:

Post a Comment