Showing posts with label while. Show all posts
Showing posts with label while. Show all posts

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.

Tuesday, May 10, 2016

do while statement

do...while statement is a little like while statement turned on its head. The essential difference between the two is that the code block is executed before condition test and not after it.

do {
// code to be executed
//increment or decrement
} while (expression of condition) ; // only if condition is true, the code block is repeated

Remember that do...while statement always ends with a semicolon.

This type of statement will be useful when we want the code block to be executed at least once, even if in while statement evaluates to false. The code block below is executed a minimum of one time:

<?php
$i = 1;
do {
echo "The number is: $i<br />";
$i++;
} while (($i > 10) && ($i < 20));
?>

The do...while statement tests whether the variable $i contains a value that is greater than 10 and less than 20. In line 2, we initialized $1 to 1, so this expression returns false. Nonetheless, the code block is executed at least one time before the condition is evaluated, so the statement will print a single line to the browser.

The number is: 1

If we change the value of $i in line 2 to something like 10 and then run the script, the loop will display
The number is: 10
The number is: 11
The number is: 12
The number is: 13
The number is: 14
The number is: 15
The number is: 16
The number is: 17
The number is: 18
The number is: 19