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

PHP Switch Statement Tutorial with Practical Example

PHP Switch Statement Tutorial with Practical Example

What is PHP Switch Statement?

According to php.net The 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  Statement Syntex

switch (n)
{
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
default:
code to be executed if n is different from both label1 and label2;
}

 

PHP Switch  Statement Practical Example

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

Coding
<?php
$n1=$_POST[‘t1’];
$n2=$_POST[‘t2’];
$ch=$_POST[‘choice’];
if(isset($_POST[‘done’]))
{
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;
}
}
?>
<html><head><title>Form</title></head>
<body>
<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>

30 Comment

Leave a Reply

Your email address will not be published. Required fields are marked *

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

Do you have any Query / Suggestion