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.
Syntax
while (condition) {
code to be executed;
}
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
1 2 3 4 5 6 7 | <?php $num = 1; while ($num <= 10) { echo $num . "<br>"; $num++; } ?> |
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.
1 2 3 4 5 6 7 | <?php $a = 11; while($a <= 3) { echo "The number is: $a <br/>"; $a++; } ?> |
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.
Result:
The number is: 11
The number is: 12
The number is: 13
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | <?php // Set the table size $size = 10; // Initialize the counters $i = 1; $j = 1; // Generate the table using a while loop echo "<table border='1'>"; while ($i <= $size) { echo "<tr>"; while ($j <= $size) { echo "<td>" . ($i * $j) . "</td>"; $j++; } echo "</tr>"; // Reset the inner loop counter $j = 1; // Increment the outer loop counter $i++; } echo "</table>"; ?> |
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.