Sunday, May 15, 2016

while statement

The while statement look like this:

while (condition/s) {
// do something
//increment or decrement to limit iteration
}

the real example is below:

<?php
$counter = 1;
while ($counter <= 10) {
echo "$counter * 10 = ".($counter * 10)."<br/>";
$counter++;
}
?>


save it as while.php and open your browser. The result should be:
1 * 10 = 10
2 * 10 = 20
3 * 10 = 30
4 * 10 = 40
5 * 10 = 50
6 * 10 = 60
7 * 10 = 70
8 * 10 = 80
9 * 10 = 90
10 * 10 = 100

its the same result as if we use "for" statement.

In this example, we initialize the variable $i, with a value of 1. The while statement tests the $i variable, so that as long as the condition(s) is true, in this case the value of $i is less than or equal to 10, the loop will continue to run. Within the while statements code block, the value of $i is multiplied by 10 and the result is printed to the browser. In line 5, the value of $i is incremented by 1. This step is extremely important, for if you did not increment the value of the $i variable, the while expression would never resolve to false and the loop would never end.