Looping in PHP – For, While and DoWhile

Loops allow you to repeat certain lines of code. The code is executed repeatedly until a condition is met. This saves you time and also decreases the number of lines of code that you need to have.

For Loop

This loop specifies the condition and repeats the statements as long as the conditions are met.


While Loop

This loop is used to specify the condition at first. If required, you will have to set the initial value and make the increments yourself.


Do While Loop

This loop is used to execute a block of code within the loop at first. Then at the end of the loop, the condition is checked. The lines of codes within the loop is executed at least once.

Difference Between While and Do While Loop

In While loop, the condition is checked at first and the statements are executed. In Do While loop, the statements are executed at first. Then the condition is checked and if it is TRUE, the loop is repeated. In Do While loop, the blocks of code are executed at least onxe even if the condition is not satisfied. While on the other hand exits the loop without performing the statements if the conditions are not satisfied from the beginning.


Note: Notice how the output from the While loop are not printed.

There is another type of loop called For Each. This loop is discussed with examples in Arrays in PHP.

You may also like

Comments are closed here.


Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 2 other subscribers