PHP / PHP Loops

It you want to run a particular block of code repeatedly we will go for using a concept of loops.

PHP looping statements:
1. while loop.
2. do while loop.
3. for loop.
4. foreach loops through a block of code for each element in an array

PHP while Loop
It will execute the block of code till the condition is true and come out of the block when the condition if false.

Syntax
while (condition is true)
{
Executes block/ line/ lines of code if one condition is true.
}

PHP while Loop
It will execute the block of code till the condition is true and come out of the block when the condition if false.

Syntax
while (condition is true)
{
Executes block/ line/ lines of code if one condition is true.
}

Program Output

Number is: 1
Number is: 2

do...while Loop
It will execute the block of code once and then it will check the condition to run the block of code or not depends on the condition is true otherwise it will come out of the loop.

Syntax
do
{
Executes block/ line/ lines of code if one condition is true.
} while (condition is true);

Program Output

Repeat Number is: 1
Repeat Number is: 2

PHP for Loop
It is used to run the block of code for a specified number of times.

Syntax
for (initialization of variables; test variables; increment / Decrement variables)
{
Executes block/ line/ lines of code if one condition is true.
}

Initialization of variables:
Initialization is Used to give start values for the variables.

Test variables:
A variable are tested and if it is true executes the block of code otherwise comes out of the loop.

Increment / Decrement variables: This section is used to increment / Decrement the variable values.

Program Output

Repeat Number is: 1
Repeat Number is: 2

PHP foreach Loop
It is used to work with arrays, and is used to loop through each key/value pair in an array.

Syntax
foreach ($array as $value)
{
code to be executed;
}

For every loop iteration, the value of the current array element is assigned to $value and the array pointer is moved by one, until it reaches the last array element.

Program Output

red
green
blue
yellow


1
2
3
4
5


Home     Back