Loading...

PHP Loops


In php loops are used for repetitive tasks untill a desired result is achieved.
For
the structure of for loop is:
for(Initialize; test; increment/decrement){
// statements
}
Initialize : here use a starting initialized variable. that is necessary for starting a loop.
test : here use a test condition variable value. loop runs untill this condition is true and stop execution when the value will return false.
increment/decrement : here use a variable value for next iterartion will follow.
for example :
            		     					     	
<?php
    for($var = 0; $var < 5; $var++){
        echo "the value is : $var <br/>";
    }
?>            		     					     		
            		     					     	
            		     					     
Output :
the value is 0
the value is 1
the value is 2
the value is 3
the value is 4


For Each
In php the for each works only on arrays.
the structure of for each loop is :
foreach(Array as Value){
// statements
}
Array : Array is a collection of values.
Value : Value is a single value in Array. which indexes sequentially.
for example :
            		     					     	
<?php
    $users = array("peter", "chris", "john", "maria", "angelina", "saturday", "sunday");
    foreach($users as $user){
        echo "the user is : $user <br/>";
    }
?>            		     					     		
            		     					     	
            		     					     
Output :
the user is : peter
the user is : chris
the user is : john
the user is : maria
the user is : angelina


While
the structure of while loop is:
while(test-condition){
// statements
increment/decrement
}
test-condition : if the test-condition is true then the code in the while loop will execute.
increment/decrement : here use a variable value for next iterartion will follow. for example :
            		     					     	
<?php
    $var = 0;
    while($var < 5){
        echo "the value is : $var <br/>";
        $var++;
    }
?>            		     					     		
            		     					     	
            		     					     
Output :
the value is 0
the value is 1
the value is 2
the value is 3
the value is 4


Do While
in do while loop the code block will execute once. it will then check the test-condition in while.
if it is true then execute or repeat the loop.
the structure of do while loop is:
do{
// statements
}while(test-condition)
test-condition : if the test-condition is true then the code in the do while loop will execute.
for example :
            		     					     	
<?php
    $var = 0;
    do{
        echo "the value is : $var <br/>";
        $var++;
    }while($var < 5);
?>            		     					     		
            		     					     	
            		     					     
Output :
the value is 0
the value is 1
the value is 2
the value is 3
the value is 4