Loops In PHP

While Loop In PHP

While loop is event control loop. its repeat executing the statement while an specific event perform. where event is an condition. The loop goes round and round while the condition is true. When the condition is false then its terminate the loop and control transfer to out side form the loop.
Syntax:
while (condition)
{
statement ;
statment2 ;
--
--
--
}
For example:
In this example we repeat the previous tutorial example in which we display the 10 number on the screen with for loop.


<?php

$counter = 1;

while ($counter <=10)

 {

echo " counter = " . $counter . "<BR>" ;

 $counter++;

}
 
 

Now we explain the execution of while loop. In this example we define a variable $counter and assign a value $counter =1. on next line while loop is start. After the keyword while we place a condition which define the execution of loop. if the condition is true in our case counter is 1 so its compare with given condition which is counter<=10, so its return true. The statements in the body of while loop will be executed. in our example 1 is printed on screen and next statement $counter++ increase the counter One time this is same as $counter=$counter+1, So counter values is now 2. After execution control again transfer to condition. which again compare the counter with given condition. Now as well as condition remain true the loop executed the statement in its body again and again. when $counter reach to 11 then loop will be terminated.