Tuesday 13 February 2018

Looping In PHP

Loops are used to execute a set of statements repeatedly until a particular condition is satisfied
The basic purpose of loop is to execute set of statements until condition becomes false and same code repeated again and again.

Advantage
It is used to reduce length of Code
It takes less memory space.
Types of Loops
There are three types of loop available in PHP
·         while loop
·         for loop
·         do-while

    While loop
In while loop  First check the condition if condition is true then the control goes inside the loop body and  print the output , It will repeated again and again until condition becomes false. If condition becomes false control goes outside the body and loop is terminated
Syntax:
assignment;
while(condition){    
Statements;   
………….
Increment/decrement (++,--)

Example:
<?php 
$x = 1;
 while($x <= 5) {
  echo "The number is: $x <br>";
  $x++;
}
?> 
Output:
The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 5 
Note: If while loop condition never false then loop becomes infinite loop


do-while
First print output then checks the condition. Since condition is checked later, the body statements will execute at least once
Syntax:
assignment;
do
{    
Statements;   
………….
Increment/decrement(++,--)
      }
    while(condition); 

Example:

<?php
$x = 1;
do {
    echo "The number is: $x <br>";
    $x++;
     }
while ($x <= 5);
?>
Output:
The number is: 1 
The number is: 2 
The number is: 3 
The number is: 4 
The number is: 5 


For loop
for loop is used to iterate a program several times and execute the code repeatedly.
We can initialize variable, check condition and increment/decrement value.
Syntax:
      for(initialization; condition; increment/decrement)
    {    
      //Statement
      }    

Example:
<?php 
for ($x = 1; $x <= 5; $x++) {
  echo "The number is: $x <br>";
}
?> 
Output:
The number is: 1 
The number is: 2 
The number is: 3 
The number is: 4 
The number is: 5 

foreach Loop
 foreach statement is used to loop through arrays.
 It is used to loop through each key/value pair in an array.
Syntax
foreach ($array as $value) {
//Statement
}
Example:
<?php 
$name = array("dev", "surya", "rakesh", "raj");
foreach ($name as $value) {
echo "$value <br>";
}
?> 
Output:
Dev
Surya
Rakesh
Raj

Break
break is used to break loop or switch statement.
Syntax:
statement;      
break;  
Example:
<?php
for($i=1;$i<=5;$i++)
{ 
 if($i==4)
{
 echo "stop";
break; 
} 
 echo "$i <br/>"; 
} 
 ?>
Output:
1
2
3
stop



No comments:

Post a Comment

apply function in R

1) apply function: It takes 3 arguments matrix,margin and function.. Example: m<-matrix(c(1,2,3,4),nrow=2,ncol=2) m #1 indicates it is ap...