While loop in PHP Syntax and Example

While loop in PHP is also used for repeating statements in PHP.

PHP while loop checks for the condition if the condition is true then code inside the body of the loop is get executed.

while – As long conditions are true, it loops back again and again through the block of code.


while (condition) {
code to be executed;

The condition is a Boolean expression that is evaluated at the beginning of each iteration of the loop.

If the condition is true, the block of code inside the loop is executed.

After the block of code is executed, the condition is evaluated again,

and if it is still true, the loop continues to iterate. If the condition is false, the loop terminates and execution continues with the next statement after the loop.

While loop in PHP Example

Example of while loop

In this example, the loop will repeatedly execute the block of code inside the loop (which prints the value of $num and increments it by 1 as long as $num is less than or equal to 10. The output of this code will be the numbers 1 through 10 printed on separate lines.

Example: Write a program to repeat the statements in PHP.

The increment and decrement while loop count variable can be used only inside loop.

For here $a++ is used to increment the value of $a.

the programmer has to take care of this otherwise while loop will be infinite.


The number is: 11
The number is: 12
The number is: 13

In this example, we first set the size of the multiplication table to 10. Then, we initialize two counters, $i and $j, to keep track of the current row and column of the table.

We then use a while loop to generate the table. The outer loop runs as long as $i is less than or equal to the table size.

Within the outer loop, we output a table row (<tr>) and start an inner loop. The inner loop runs as long as $j is less than or equal to the table size.

Within the inner loop, we output a table cell (<td>) that contains the product of $i and $j. We then increment $j to move to the next column.

After the inner loop completes, we close the table row (</tr>) and reset the inner loop counter $j back to 1. Finally, we increment the outer loop counter $i to move to the next row.

Write a PHP program to reverse the digits of numbers

Read More

PHP for and for each loop statement

PHP does while loop statement with syntax and example