while loop php | php tutorial | learn php online

– While loop in php is used to execute a statement or set of statements while the condition evaluates to true.

– while loop is generally used when we do not know how much time a statement needs to be executed.

– the statement block is executed until statement evaluates to false.

In php there are two variants in while loop –

– do….while loop

– while loop

do……while loop php

do…..while loop is post-condition check. The statement is executed and then the condition is checked.

In this loop, if condition evaluates to false, still statement block is executed atleast once.

Syntax

Example

In the above example, the echo statement is executed first, then the value of $i is incremented by one. After this the condition is evaluated, if the condition is false, the loop will not execute further.

Output

1
2
3
4
5

while loop

while loop is pre-conditon check. The condition is evaluated first and then only if the condition is evaluated to true.

In this case the statement is not executed not even once, if the condition is false.

Syntax

Example

In the above example, the condition is evaluated first and then only if the condition evaluates to True, the loop is executed.

Output

1
2
3
4
5

Also check Loops in php

Author: Deepak Kumar

This is Deepak Kumar, founder of True Infosystems and of-course the chief content creator at CodingLessions.info. Started my carrier as a Freelancer and now a top-rated Freelancer at Upwork, delivered over 200 successful projects with highly positive user ratings and counting.