PHP 5 while loops are used to run the same block of code several time. In some situation, you require adding a block of code repeatedly. In this case, the while loops work best.
You can avoid adding the same block of code again.

Example

[php]<?php
$x = 1;

while($x <= 10) {
echo "The number is: $x <br>";
$x++;
}
?>[/php]

In the above while loop, we have mentioned the variable $x and given the value 1. We have mentioned the condition if $x is small than or equal to 10. The echo statement will execute the code as per the condition and then we have mentioned it should increment by one each time until it reaches the 10 as per the above condition. If We change the 10 to 20 then while loop will run until it reaches the number 20.

The above will generate the following result.

The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 5
The number is: 6
The number is: 7
The number is: 8
The number is: 9
The number is: 10

Related Posts

Leave a Reply