What is Loop in Php and its type ?

In general term , the loop is the repeated process of same instruction until it is ordered to stop the execution .

Types of Loop .

1 . Do Loop :
Do loop is the statements in the program is pre-defined task that executes its execution until met to the  predetermined conditions .

For Example :

<?php 
 $counter = 0;
do {
     print “$countern”;
     $counter++;
} until ($counter >= 21);

?> 

Here , the counter is initialized 0 and will iterate till it meet to counter 21 .
Make sure , the condition will always meet to prevent from the endless Loop

As similar , Do While  Loop
Do While  Loop always execute once , than it check the condition and repeat  loop until the contrition gets true .

Syntax :

do {
    code to be executed;
} while (condition is true);


2 . While Loop
   While loop is the loop that executes the nested statements ( block ov code ) repeatedly as long as the while loop evaluates the statement  (condition ) is true .

Syntax

while (exprn):
    statement
    statement
    …
endwhile;

Example :

<?php 
$a = 10;

while($a <= 50){

    echo “The number is: $a <br>”;
    $a++;

?>

3 . For Loop :
In case of the For loop the execution of the block of code is specified  or it is previously know that how many times the script should run.

Syntax for for loop : 

for (init counter; test counter; increment counter) {
    code to be executed;
}

<?php 
for ($a = 1 ; $a <= 10; $a++) {
    echo “The count is: $a <br>”;

?>

4 . For Each Loop : 
The for each loop is especially used for looping through the array values , it loops over array each values of an current element is assigned to variables  ( $value ) and array pointer is advanced and go to next element and this process process over a time in loop .

Syntax

<?php  foreach ($array as $key=> $value ){    //code to be executed here ; }  ?>

   

Leave a Reply

Your email address will not be published.Required fields are marked *