PHP While loops

While loop in PHP, is another efficient way to execute task in loop. While loop can also be considered to alternative to for loop.

While Loop:

While loop is used to execute task in loop.

While loop syntax:

initial value

while (condition){

// execute required task

// what should it do at the end of a loop Increment / Decrement


If you are not aware why loops are used then read: PHP for loops


Lets print 1 to 100 using while loop.

Before using while loop, we need to understand three required factors for the while loop.

Once we know above three factors, then we are ready to use while loop.

Remember, the task here is to print the value in each loop.

The code is:




echo $i;




The above code prints 1 to 10.

What is happening in the while loops?

This way, while loop works.


While using ‘while loop’, you have to be very careful. If you forget to mention the initial value, condition and increment or decrement operation then it would land into infinite loop.