Generic selectors
Exact matches only
Search in title
Search in content
Post Type Selectors

How can we use while loop in PHP ? Give example

In PHP, we can use the while loop to execute a block of code repeatedly while a certain condition is true.

The syntax of the while loop is as follows:

while (condition) {
    // code to be executed

Here, condition is the condition that we want to check. The code inside the loop will be executed repeatedly as long as the condition is true.

Here’s an example that demonstrates how to use a while loop in PHP:


$i = 1;
while ($i <= 10) {
    echo $i . "<br>";



In this code, we define a variable $i with a value of 1. We then use a while loop to output the value of $i and increment it by 1 on each iteration. The loop continues to execute as long as $i is less than or equal to 10.

When we run this code, it will output the numbers 1 to 10 on separate lines.

The while loop is useful when we need to execute a block of code repeatedly as long as a certain condition is true. It is often used when we don’t know in advance how many times the loop will need to execute. However, we need to be careful to avoid infinite loops, which can occur if the condition never becomes false.