PHP FORM Part-8


 

PHP FORM Part-8

The construction of while loop in PHP is lot easier than the for loop function of PHP. We need to evaluate the only one condition at one time. The loop moves round till the condition is true, immediately it comes out when the condition is false.

The construction of while loop in PHP is lot easier than the for loop function of PHP. We need to evaluate the only one condition at one time. The loop moves round till the condition is true, immediately it comes out when the condition is false.

Topic : HTML FORM While Loop

Part - 8

In this part of tutorial, we will learn about the While loop. Instead of using for loop, we can also use while loop to move the condition round.

The construction of while loop is lot easier than the for loop. We need to evaluate the only one condition at one time. The loop moves round till the condition is true, immediately it comes out when the condition is false.

The syntax for a while loop in PHP is :

initialize = value;   

while (condition) {
        statement;
    }

 Let's see the example code to understand in a better way :

<?php

$num = 1;

while($num<11) {

echo $num."<br/>";

$num++;

}

?>

The output of the above code is : 1
2
3
4
5
6
7
8
9
10

The first step is to initialize the variable to any value. Here, we initialized the $num variable to value 1. And, then we mentioned the name of the loop i.e. While. Within the round bracket, we give the condition $num<11. If the $num is less than eleven then the condition is true otherwise it comes out, if the $num is greater than eleven.

 The condition will false and the while loop will stop moving round and round. Each time the while loop moves round and round to checked the condition, whether, it is true or false.

It could be complicated, if you don't provide the way for your condition to be evaluated as true because it will create an infinite loop and your condition will stuck at the same value. 

Let's see the example below :

<?php

$num = 1;

while($num<11){

echo $num."<br/>";

//$num++;

}

?>

If you noticed the two forward slashes before $num++. This line will now be ignored. Because the loop is going round and round while num is less than 11, the loop will never end ? $num will always be 1.

In the next part of this tutorial, we will learn about the Do...While loop.


Ads