PHP Switch Statement - php mvc - Phptpoint.com

PHP Switch Statement

/ins>

Switch Statement in PHP

The switch statement is similar to a series of if statements on the same expression.

The following two examples are two different ways to write the same thing, one using a series of if and else-if statements, and the other using the switch statement.

Output
2 equals 2
2 equals 2

In the given example
$i is a variable hold the value = 2, switch statement worked same as nested if else work.
if condition check($i==2), matched so the output will : 2 equals 2.
same for switch($i) matched the case 2: so the output will : 2 equals 2.


switch statement without break

Output
0 equals 0
0 equals 1
0 equals 2

variable($i) hold the value=0. this value pass inside the switch. it start match the case.
first case is match with initially declare variable value(0).
All statement are execute from case:0 to case:2.


Switch case may contain empty statement, then it simply passes the control  for next case.

Output
1 is less than 3 but not negative

Initialize a variable($i) with value=1.Now pass this value inside the switch statement.

Now case start to match the value of initialize variable($i). As case:1 is match.but their is no statement for execution.

so it will skip the case because of break is absent in case:1. Now case:2 statement is execute and break terminate the program.

Output will become case:2 (statement) : 1 is less than 3 but not negative.


Use of Default in Switch Statement

In case any switch case doesn’t matches then executes default statement.

Output
5 is not equal to 0, 1 or 2

In the given example
$i is variable hold value = 5.

now switch condition execute with variable $i. Here three case is define.

it check the value for case0, case1 and case2. But only default condition is execute because all three case do not match.

and Output display : 5 is not equal to 0, 1 or 2


Enter first number second number and choice, make calculation.

Output
Sum=1000
Enter first number
Enter second number
Enter Your choice

In the above example
first we create the form using HTML script to take input from users.

Inside the form ,we create three textbox and a submit button.

Program logic define inside the PHP script. Variable($f, $s , $choice) are declare to hold the value that is collect by using $_POST[ ] .

$choice is used to perform(Add/Multiply/Divide/substract) operation.

First Number input is 500
Second Number input is 500
Choice input is “+”

Inside the choice text box inputted value is +, so it will match the first case and execute first case(+).
Output display : Sum=1000