IF ELSE syntax :
IF (CONDITION)
{
BLOCK OF CODE TO BE EXECUTED ;
}
ELSE
{
BLOCK OF CODE TO BE EXECUTED ;
}
IF ELSE EXAMPLE :
<?php
$color=”red”;
if($color==”red”)
{
echo “color is red”;
}
else
{
echo “not red color”;
}
?>
PHP – The if…elseif ….else Statement :
Use the if….elseif…else statement to specify a new condition to test, if the first condition is false.
Syntax :
IF (CONDITION)
{
BLOCK OF CODE TO BE EXECUTED ;
}
ELSE IF(CONDITION)
{
BLOCK OF CODE TO BE EXECUTED ;
}
ELSE
{
BLOCK OF CODE TO BE EXECUTED ;
}
Example :
<?php
$color=”red”;
if($color==”red”)
{
echo “color is red”;
}
else if($color==”orange”)
{
echo “color is orange”;
}
else
{
echo “No color:”;
}
?>
The PHP switch Statement
Use the switch statement to select one of many blocks of code to be executed.
Syntax :
Switch (n)
{
Case Label 1:
Code to be executed if n=Label1;
Break;
Case Label 2:
Code to be execute if n=Lable2;
Break;
……..
Default:
Code to be executed if n is different from all Labels;
}
note: here “n” is values which match with all Case Label1, Label2..
Example :
<?php
$color=”white”;
switch($color)
{
case “red”:
echo “color is red”;
break;
case “blue”:
echo “color is blue”;
break;
case “orange”:
echo “color is orange”;
break;
default:
echo “no color”;
break;
}
?>
===================
SIMPLE APPLICATION FOR PRACTICE USING SWITCH SIMPLE CALCULATOR :
(1)write code for form.html:
<html>
<head>
<title>simple calculator</title>
</head>
<body>
<form action=”cal.php” method=”post”>
enter value of a<input type=”text” name=”a”>
enter value of b<input type=”text” name=”b”>
<select name=”cal”>
<option value=”add”>Addition</option>
<option value=”sub”>Subtraction</option>
<option value=”mul”>Multiplication</option>
</select>
<input type=”submit” name=”submit” value=”cal”>
</form>
</body>
</html>
(2)write code for “cal.php” :
<?php
$cal=$_POST[“cal”];
$a=$_POST[“a”];
$b=$_POST[“b”];
if($cal==”add”)
{
$c=$a+$b;
echo”it is addition”.$c;
}
else if($cal==”sub”)
{
$c=$a-$b;
echo”it is subtraction”.$c;
}
else if($cal==”mul”)
{
$c=$a*$b;
echo”it is multiplication”.$c;
}
else
{
echo”no calculation”;
}
?>
OUTPUT:
see output AFTER CLICK ON CAL BUTTON ..