Decision Making Statements

There are various types of conditional statements available in PHP –

  1. if statement
  2. if-else statement
  3. if-elseif-else statement
  4. switch statement

Let us illustrate each of them with intuitive real world examples,

1. The if Statement

The syntax of the if statement is something like this,

if(condition){
  //statements to be executed if the condition is true
  }

2. The if-else Statement

The syntax of the if statement is something like this,

if(condition){
//Statements to be executed if the condition is true
}
else{
//Statements to be executed if the condition is false
}

3. The if Statement

The syntax of the if statement is something like this,

 if(condition){
//Statements to be executed if the condition is true
}
elseif(another_condiiton){
//Statements to be executed if the other condition is true
}
else{
//Statements to be executed if none of the conditions are true.
}

4. The switch Statement

Switch statement proves to be a very useful decision-making statement if we have multiple expressions to be evaluated. It is much simpler and quicker to write codes using switch statement rather than a long set of if-elseif-else statements.

The syntax for the switch statement is a bit different from the others –

switch (n)
{
case tag1:
code to be executed if n=tag1;
break;
case tag2:
code to be executed if n=tag2;
break;
case tag3:
code to be executed if n=tag3;
break;
...
default:
code to be executed if n is different from all tags;
}

Example
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<?php
$flagA=false;
$flagB=false;
 if( isset($_POST["submit"]))
 {
    	$n=$_POST["txtper"];
		if(  ! empty($n)  && is_numeric($n))
		{
		$flagA=true;
			if( $n>=60)
			{
			$grade=" First Div";
			}
			else if($n>=45)
			{
				$grade="Second Div";
			}
			else if($n>=33)
			{
				$grade="  Third Div";
			}
			else
			{
				$grade="  Fail";
			}
		
		}
		else
		{
			$flagB=true;
			$err= "Value  Not Given/ Number format error";
		}
	
 }
?>

 <center>
 <form  action="<?php $_PHP_SELF ?>" method="post">
 <br/> Enter  Percentage   <input type="text" name="txtper" />
 <br />
  <br />
 <input type="submit"  name="submit"  value="send it now.."/>
 </form>	
  <br />
   <br />
    <?php
	
	if( $flagA==true)
	{
	?>
        
	 <div  style="width:300px; margin:auto; border:1px solid  #963; background-color:#C69;color:white">
   	 <?php	echo $grade; ?>
	 </div>
     
     <?php
	}
	else if ( $flagB==true)
	{
	?>	
    
   
     <div  style="width:300px; margin:auto; border:1px solid  #963; background-color:red;color:yellow">
	 <?php	echo $err; ?>
     </div>
    
    
    <?php
	}
	?>
	
 
<center/>
</body>
</html>

output..

kk

 

when you enter  non numeric / blank then...

kk2