Monday 12 February 2018

Control statements in PHP

Control statements are used to control and execute the statements based on certain conditions or repeat a group of statements until certain specified conditions are met
There are different types of if statements in PHP.
·                     if statement
·                     if-else statement
·                     nested if statement
·                     if-else-if ladder

if Statement:
if statement checks the condition. It is executed if condition is true.
Syntax:
if (condition){    
        //statement
             } 
Example:
<?php
$num=12; 
if($num%2==0)
{ 
echo "$num is even number"; 
}
 ?>
Output:
12 is even number

if-else Statement
If-else statement checks the condition. It executes if condition is true otherwise it comes to else block and else block will be executed.
Syntax:
     if(condition){    
     //statement
         }
         else{    
        //statement
            }    
  Example:
<?php
$num=12; 
if($num%2==0)
{ 
echo "$num is even number"; 
}
else
{ 
echo "$num is odd number"; 
} 
?>
Output:
12 is even number

If-else-if ladder Statement
if-else-if ladder statement executes one condition from multiple conditions.It will check the conditions one by one ,if the condition is true then print the output otherwise it comes to  else block and else block will be executed.
Syntax:
  if(condition1){   
     / /statement
}   
     else if(condition2){    
     //statement
}  
     else if(condition3){    
      //statement
 }   
       ...........................    
  else{    
     //statement
        }
  Example:
   <?php
  $num=-12; 
  if($num>0)
  { 
echo "$num is positive number"; 
   }
else if($num<0)
{ 
echo "$num is negative number"; 
} 
else{
  echo "number is zero";
   }
?>
Output:
-12 is negative number

switch
switch statement executes one statement from multiple conditions. It will check the conditions one by one. If it finds true, it will print the output otherwise it comes to default and default statement will be executed. It is just like if-else-if ladder
Syntax:
switch(expression){      
case value1:      
 //statement
 break;    
case value2:      
 //statement
 break;    
......      
      
default:       
 //statement
}    
 Example:
<?php
 $num=7;   
switch($num){   
case 1:   
echo("Hello");   
break;   
case 2:   
echo("HI");   
break;   
case 3:   
echo("Welcome");   
break;
default:   
echo("invalid");   
}
?>
Output:
invalid

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...