Monday, February 9, 2015

PHP Loops and their usage with example


PHP loops are used to execute a block of code for a specific number of times. It is very popular among coders and programmers as it reduces the effort and time to execute a script or scripts.

For loop:

For loop is used to run a single script for multiple times. It is used when you know how many times the script should run.
Syntax:
 for (initialization; condition; increment)  
 {  
  Here is code to be executed;  
 }  


Example:
For loop:
 <?php  
 /*Example of for loop*/  
 for ($i = 1; $i < 10; $i++) {  
   echo $i;  
   echo "<br/>";  
 }  
 ?> 

Do while loop:
This loop loops through a block of code once, and repets the loop as long as the condition is true.

Syntax:
do  
 {  
   Here is code to be executed;  
 }while (condition); 
Example:
PHP Script (do-while.php)
 <?php  
 /*Example of do-while loop*/  
 $i=0;  
 do {  
   $i++;  
   echo "$i";  
   echo "<br/>";  
 } while ($i < 10);  
 ?>

While loop:
This loop loops through a block of code as long as the given condition is true.


Syntax:
 while (condition) {  
   this is the code to be executed;  
 } 

Example:

PHP Script (while.php)
 <?php  
 $i = 1;  
 /*Example of while loop*/  
 while($i <= 15) {  
   echo "$i <br>";  
   $i++;  
 }  
 ?>  

Foreach loop:
It loops through a block of code for each element in an array.
Syntax:
 foreach ($array as $value) {  
   code to be executed;  
 }

Example:

PHP Script (foreach.php)
 <?php  
 /*Example of foreach*/  
 $arr = array("1","2","3","4","5","6","7","8","9","10","11","12");  
 foreach($arr as $value){  
   echo $value;  
   echo "<br/>";  
 }  
 ?>  

Syntax:
 foreach ($array as $value => $assoc_value) {  
   code to be executed;  
 }  

Example:

PHP Script (foreach-assoc.php)

<?php  
 /*Example of foreach for associative array*/  
 $age = array("HTML"=>"Hypertext Markup Language", "CSS"=>"Cascading Style Sheets", "PHP"=>"Hypertext Preprocessor");  
 foreach($age as $x => $y) {  
   echo "$x", " = " . $y;  
   echo "<br>";  
 }  
 ?>  

No comments:

Post a Comment