While loop in PHP, is similar to for loop, but initialization is done outside of while loop and iteration is done inside loop body.
Syntax
In PHP, while has two different syntax
initialization;
while(condition){
// Code/set of statements
iteration;
}
expr1;
while (expr2){
statement
expr3;
}
Second syntax
initialization;
while (condition):
// Code/set of statements
iteration;
endwhile;
Second syntax uses : colon in place of opening curly brace, and endwhile keyword and semi-colon; in place of closing curly brace
While loop has four parts
initialization | Starting value or number from where while loop starts. It is the first statement and should be outside of while loop. |
condition | It tests condition, if true executes the statements inside loop body, else not. |
iteration | It is used to continue the while loop, until condition becomes false, It can be increment or decrement. It should be inside loop body. |
Statements | These are line of codes, enclosed inside curly braces { }. single statement does not requires curly braces. |
Example
<?php
$n = 1;
while($n <= 10){
echo $n;
$n++;
}
?>
Second way of using while loop
<?php
$n = 1;
while ($n <=10):
echo $n;
$n++;
endwhile;
?>
In second way of using while loop, in place of curly braces {}, colon : and endwhile with semicolon is used.