PHP While Statement
The While Statement loops a block of code until it the condition becomes false.
Syntax
while (expression){
Execute code;
}
The While Statement will execute if the expression evaluates to true. For example, we will make a variable, call it A and set it to 1, and say if A is less than 50, increment it until it reaches 50.
Example
<ul>
<?php
$A = 1; //Set your variable
while ($A < 50){ //A is less than 50?
$A++; //Increment it, until it reaches 50
echo '<li>'. 'My number is '.$A.'</li>'; //Print out the numbers.
}
?>
</ul>
Code Explained
- First we wrapped the PHP code in an unordered list
- Declared the variable A and set it to 1
- Then we said if A is less than 50, increment it and echo out the result
Breaking from Loops
This time we will break from the loop when a specific number has been reached.
<ul>
<?php
$num = 1;
while ($num < 350){
$num++;
if ($num == 250){
break;
}else{
echo '<li>'.$num.'</li>';
}
}
?>
</ul>
Code Explained
- Like before, we increment $num++
- We then have an If Statement saying if $num is equal to 250
- STOP (break;)
- If Else, print out the numbers in an unordered list
