PHP Confitional Statement

Sujitha

PHP if...else...elseif Statements

PHP Confitional Statement

         You can use conditional statements to make decisions in your code.

The most common ones are:

 
If statememt:
      Executes a block of code if a specified condition is true.

Syntax

If( condition)
{
//code to execute if condition is true
}

Example

?php  
$num=15;  
if($num<50){  
echo "$num is less than 100";  
}  
?> 
// output 15 is less than 100

If-else statement:
         Executes one block of code if the condition is true and another if it's false.

Symtax:

if (condition) {
    // Code to execute if the condition is true
} else {
    // Code to execute if the condition is false
}

Example

php  
$num=112;  
if($num<100)
{  
echo "$num is lesser than 100";
}
else
{
echo "$num is greater than 100";
}  
?>
//output 112 is greater than 100

If-else if-else statement:
        Allows you to check multiple conditions and execute different code blocks accordingly.

Syntax

if (condition1)
{
    // Code to execute if condition1 is true
}
elseif (condition2)
{
    // Code to execute if condition2 is true
}
else
{
    // Code to execute if neither condition1 nor condition2 is true

Example

<?php  
$marks=74;      
if ($marks<33)
{    
echo "fail";    
 }    
 else if ($marks>=50 && $marks<65)
 {    
 echo "C grade";   
 }    
 else if ($marks>=65 && $marks<80)
 {    
 echo "B grade";   
 }    
 else if ($marks>=80 && $marks<90)
{    
 echo "A grade";    
}  
else if ($marks>=90 && $marks<100)
{    
echo "A+ grade";   
}  
else
{    
echo "Invalid input";    
}    
?>
//output B grade



Our website uses cookies to enhance your experience. Learn More
Accept !

GocourseAI

close
send