While loop in PHP is very simple and similar to while loop in C programming. In PHP while loop the condition is checked at the beginning of the loop and the statement inside is executed till the end of the loop, then again the condition is checked and loop executed. Like this loop
is continued till the condition became false and the loop is then stopped.
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. Here is one simple example of while loop.
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
Here we are checking the while condition at the starting of the loop. So the execution of the loop will be done only if condition is satisfied at the beginning. We can read on the difference between do while loop and while loop here. Exit inside the loop by using break
Prematurely we can come out of the loop by using break statement. We used one if condition to check the value and then apply break statement.
Using NULL
Check this code$a=NULL;
while[$a]{
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.However below code will print the output once, as we have used
break;
to come out of the loop after printing hi. $a=True;
while[$a]{
echo "hi";
break;
}
Display elements of an array by using While loop
Let us declare one array with some elements. Then by using while loop we can display the key and value of the array.
The
output is here 0 > Three
1 > two
2 > Four
3 > five
4 > ten
Create [ 2 to 10 ]multiplication table using While loop
To generate multiplication tables we will start with 2 tableHere is the simple code
$i=2;
$j=1;
while[$j
Run Program
Multiplication Table in PHP using Function
Run Program
Output
----The input number is: 15
----The range number is: 12
----The above multiplication table--------
15 * 1 = 15
15 * 2 = 30
15 * 3 = 45
15 * 4 = 60
15 * 5 = 75
15 * 6 = 90
15 * 7 = 105
15 * 8 = 120
15 * 9 = 135
15 * 10 = 150
15 * 11 = 165
15 * 12 = 180