In this tutorial, you will learn about PHP while Loop step by step. So without much to do, let’s get started.
The while loop – Loops through a block of code as long as the specified situation is true.
The PHP whilst Loop
The while loop executes a block of code as long as the specified condition is true.
Syntax
while (condition is true) { code to be executed; }
Examples
The example below displays the numbers from 1 to 5:
Example
<!DOCTYPE html> <html> <body> <?php $x = 1; while($x <= 5) { echo "The number is: $x <br>"; $x++; } ?> </body> </html>
Example Explained
• $x = 1; – Initialize the loop counter ($x), and set the start value to 1
• $x <= five – Continue the loop so long as $x is less than or equal to 5
• $x++; – Increase the loop counter value by 1 for each iteration
This example counts to 100 by tens:
Example
<!DOCTYPE html> <html> <body> <?php $x = 0; while($x <= 100) { echo "The number is: $x <br>"; $x+=10; } ?> </body> </html>
Example Explained
• $x = 0; – Initialize the loop counter ($x), and set the begin cost to 0
• $x <= 100 – Continue the loop as long as $x is less than or equal to 100
• $x+=10; – Increase the loop counter value by way of 10 for each iteration
READ NEXT
This is about PHP while Loop, and we hope you have learned something from this tutorial and share your opinion about this tutorial. What do you think about it, and if you think this tutorial will help some of your friends, do share it with them.