PHP – Loops

Loops in PHP

In this chapter we will know what are loops and why we use loops in our program.

In any program loops play an important role to complete any specified task. Mainly loops are used to execute a block of program several times until it matches the specified condition.

In PHP, we use mainly four loop types given below:

for − loops repeat a block of code in a program to a predefined number of times.

while − loops first test the condition and then repeat a block of code in a program until a specified condition is true.

do…while − loops first repeat a block of code in a program and the conditional staement is tested at the end of the loop.

foreach − loops mainly used to retrieve the arrays elements and reapeat a block of program for each array element.

The for Loop in PHP

The “for loop” is mainly used when we know in advance that how many times we need to repeat the code of a program. In “for loop”, we need to define the starting and end point before starting the loop.

for loop SYNTAX

for loop parameters

loop initialization: we will initialize the loop counter value using a variable name and assign the numeric value.
loop counter: here we will define how many times loop will run.
increment counter: here we will define the loop increment counter.

You can understand this with the following example:

The while loop in PHP

The while loop in PHP executes a block of a program until the specified condition returns true.

while loop SYNTAX


The do…while loop in PHP

The do…while loop will execute the block of code and then match the specified condition. The loop will be executed until the condition returns true results.

do…while loop SYNTAX


The foreach loop in PHP

The foreach loop is used only on arrays and repeat the block of code for each array key pair.

The foreach loop SYNTAX




Leave a Reply

Your email address will not be published.