Like Us Like Us Facebook Subscribe Subscribe us YouTube Whatsapp Share us Whatsapp Query Send your queries

Using PHP Switch Statement / Case

Using PHP Switch Statement / Case

The PHP switch statement is similar to a series of IF statements on the same expression. In many occasions, you may want to compare the same variable (or expression) with many different values, and execute a different piece of code depending on which value it equals to. This is exactly what the switch statement is for.

PHP Switch Case / Statement Examples given below

Question: Write a program to enter two number and select task from list then display the result.

Solution:

pro1.php

<!DOCTYPE html><head><meta charset=”utf-8″><title>Form</title></head>
<body>

<?php
if(isset($_POST[‘done’]))
{

$n1=$_POST[‘t1’];
$n2=$_POST[‘t2’];
$ch=$_POST[‘choice’];
switch($ch)
{
case ‘add’:
$res=$n1+$n2;
break;
case ‘sub’:
$res=$n1-$n2;
break;
case ‘mul’:
$res=$n1*$n2;
break;
case ‘div’:
$res=$n1/$n2;
break;
}
}
?>
<form action=”” method=”post”>
Enter First Number<input type=”text” name=”t1″><br>
Enter Second Number<input type=”text” name=”t2″><br>
Result<input type=”text” value=”<?php echo $res;?>”><br>
Select Task<select name=”choice”>
<option value=”add”>ADD</option>
<option value=”sub”>SUB</option>
<option value=”mul”>MUL</option>
<option value=”div”>DIv</option>
</select><br>
<input type=”submit” name=”done” value=”DONE”>
</form>
</body>
</html>

Question: Write a program to enter two number and select task through radio button then display the result.

Solution:

pro2.php

<!DOCTYPE html><head><meta charset=”utf-8″><title>Form</title></head>
<body>

<?php
if(isset($_POST[‘done’]))
{

$n1=$_POST[‘t1’];
$n2=$_POST[‘t2’];
$ch=$_POST[‘choice’];
switch($ch)
{
case ‘add’:
$res=$n1+$n2;
break;
case ‘sub’:
$res=$n1-$n2;
break;
case ‘mul’:
$res=$n1*$n2;
break;
case ‘div’:
$res=$n1/$n2;
break;
}
}
?>
<form action=”” method=”post”>
Enter First Number<input type=”text” name=”t1″><br>
Enter Second Number<input type=”text” name=”t2″><br>
Result<input type=”text” value=”<?php echo $res;?>”><br>
Select Task:&nbsp;&nbsp;&nbsp;
<input type=”radio” name=”choice” value=”add”>ADD
<input type=”radio” name=”choice” value=”sub”>SUB
<input type=”radio” name=”choice” value=”mul”>MUL
<input type=”radio” name=”choice” value=”div”>DIV<br>
<input type=”submit” name=”done” value=”DONE”>
</form>
</body>
</html>

0 0 votes
Article Rating
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments