Domesticated Brain

PHP Loops

Before we go through the PHP loops it’s better to get an idea about the loops in computer programming

In computer programming a loop is a series of instructions that should be repeated until a certain condition is true. In other words it has to continue until the condition is reached

In PHP programing there are four loops to be taken under consideration

That is – While loop / for loop / Do while loop/ foreach loop 

 

PHP While loop

A while loop executes a block of code while the specified condition is true

As an example, the program will execute the block of code (echo "$num &nbsp ";) while the specified condition ($num <= 10) is true

PHP While loop

 

<?php

$num = 1;

while($num <= 10){

echo "$num &nbsp ";

$num++;

}

?>

 

Output of the above PHP program is–

1 2 3 4 5 6 7 8 9 10

 

PHP For loop

We use for loops when we want to run a block of code for a specified number of times in a program 

The for loop is used when you know how many times the script should run in your program

In following example the program will execute the block of code (echo "hello world". "</br>";) four times

PHP For loop

 

<?php

for ($num=1; $num<=4; $num++){

                echo "hello world". "</br>";

}

?>

 

 Output of the above PHP program is –

 hello world

 hello world 

 hello world

 hello world 

 

PHP Do while loop

The do...while execute the block of code once and then check the specified condition and continues until the condition is fulfill

PHP Do while loop

 

<?php

$num = 1;

do{

   echo $num. "</br>";

  $num++;

}

while($num<=10);

?>

 

Output of the above PHP program is –

1
2
3
4
5
6
7
8
9
10

 

PHP foreach loop

We used for each loop in php programing when we want to loop through each value in an array

Note that foreach loop works only on arrays in php programming

 

Syntax

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

 

In following example the value of the present array element(BMW) assinged to $value and move  up to the last array element (Ford) passing each element one after the other.

 

<?php

$vehicle_types = array("BMW", "Peugeot", "Benz", "Ford");

foreach ($vehicle_types as $value) {

    echo "$value <br>";

}

?>

 

Output of the above PHP program is –

BMW
Peugeot
Benz
Ford

For more details, Please refer the PHP manual and the W3Schools web site.

If you have found  what you expected please comment and like on our facebook page