<?Php
$j=5; // assigned a value to the variable
while($j <10 ){ // loop starts if condition is true
echo " value of \$j= $j <br>";
$j=$j+1; // increment by 1
}
?>
What is the output of this?
value of $j= 5
value of $j= 6
value of $j= 7
value of $j= 8
value of $j= 9
while(condition checked){
code part to execute
}
Here if the condition became false inside the loop then also the loop continue to execute till the next time
the condition is checked.
<?Php
$j=1; // assigned a value to the variable
while($j <10 ){// loop starts if condition is true
echo " value of \$j= $j <br>";
if($j==7){
break; // come out of the loop
}
$j=$j+1; // Increment by 1
}
?>
Output ( value more than 7 is not printed )
value of $j= 1
value of $j= 2
value of $j= 3
value of $j= 4
value of $j= 5
value of $j= 6
value of $j= 7
$i=0;
while ($i<=10){
$i=$i+1;
if($i == 5){continue;}
echo $i."<br>";
}
This will print 1 to 11 without printing number 5.
set_time_limit ( 3 );// set maximum execution time in seconds
$i=1;
while ($i<=10){
if($i == 5){continue;
echo $i."<br>";
$i=$i+1;
}
}
$a=NULL; // Assigned vlaue
while($a){ //Checking True condition
echo "hi";
break;
}
In above code the line echo "hi";
will not be executed as NULL is same as False. This concept we will be using in database record set where pointer will return NULL when there is no more record to return.break;
to come out of the loop after printing hi.
$a=True;
while($a){
echo "hi";
break;
}
<?Php
$a= array("Three", "two", "Four", "five","ten");
while(list($key,$val) = each($a) ){
echo $key . " > ". $val . "<br>";
}
?>
The output is here
0 > Three
1 > two
2 > Four
3 > five
4 > ten
$i=2;
$j=1;
while($j<= 10){ // Inner Loop
echo $i*$j." | ";
$j=$j+1;
}
This will display 2 table like this
2 | 4 | 6 | 8 | 10 | 12 | 14 | 16 | 18 | 20 |
$i=1;
$j=1;
while($i<= 10){ // Outer Loop
while($j<= 10){ // Inner Loop
echo $i*$j." | ";
$j=$j+1;
} // End of Inner loop
echo "<br>";
$j=1;
$i=$i+1;
}// End of outer loop
Output is here. ( Multiplication table from 2 to 10 )
1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |
2 | 4 | 6 | 8 | 10 | 12 | 14 | 16 | 18 | 20 |
3 | 6 | 9 | 12 | 15 | 18 | 21 | 24 | 27 | 30 |
4 | 8 | 12 | 16 | 20 | 24 | 28 | 32 | 36 | 40 |
5 | 10 | 15 | 20 | 25 | 30 | 35 | 40 | 45 | 50 |
6 | 12 | 18 | 24 | 30 | 36 | 42 | 48 | 54 | 60 |
7 | 14 | 21 | 28 | 35 | 42 | 49 | 56 | 63 | 70 |
8 | 16 | 24 | 32 | 40 | 48 | 56 | 64 | 72 | 80 |
9 | 18 | 27 | 36 | 45 | 54 | 63 | 72 | 81 | 90 |
10 | 20 | 30 | 40 | 50 | 60 | 70 | 80 | 90 | 100 |
Increase the condition values to expand the above table.
$i=1;
while($i<5):
echo $i;
$i=$i+1;
endwhile
Output is here
1234
PHP LoopsPHP Do While loop
For loop
Switch for matching code block in PHP if else condition checking
15-06-2020 | |
I want to know if there's one that loops through a mysql database |
24-06-2020 | |
Yes, we can fetch records as per the query and then loop through them to display. Check the PHP MySQL section for more details. |