Home >>PHP Tutorial >PHP Switch Statement

PHP Switch Statement

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.

<?php	
		
$i=2;
		
if ($i == 0)
		 
{
			
echo "$i equals 0 ";
		
}
	    
else if ($i == 1)
		 
{
			
echo "$i equals 1 ";
		 
}
		 
		 
else if ($i == 2) 
		 
{
			
echo "$i equals 2 ";
		  
}

//using switch
switch ($i)
		 
{
		  
case 0:
			
echo "$i equals 0 ";
			
break;
		  
case 1:
			
echo "$i equals 1 ";
			
break;
		  
case 2:
			
echo "$i equals 2 ";
			
break;
		
}

?>
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

<?php
	
$i=0;
	
switch ($i) 
	
{
		
case 0:
			
echo "$i equals 0"."<br/>";
		
case 1:
			
echo "$i equals 1"."<br/>";
		
case 2:
        		
echo "$i equals 2"."<br/>";
	
}

?>

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.

<?php
	
$i=1;
	
switch ($i)
	
{
		
case 0:
		
case 1:
		
case 2:
			
echo "$i is less than 3 but not negative";
			
break;
		
case 3:
       		
echo "i is 3";
 	  
}

?>

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.

<?php
	
$i=5;
	
switch ($i)
	 
{
     	
case 0:
		
echo "i equals 0";
		 
break;
        
case 1:
		 
echo "i equals 1";
		 
break;
        
case 2:
		
echo "i equals 2";
		 
break;
        
default:
       	 
echo "i is not equal to 0, 1 or 2";
	
}

?>

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.

<?php
 	
$f=$_POST['f'];
	
$s=$_POST['s'];
	
$choice=$_POST['ch'];
	
switch ($choice)

{

case "+":
			
$sum=$f+$s;
			
echo "Sum=".$sum;
			
break;
		  
case "-":
			
$sub=$f-$s;
			
echo "Subtraction=".$sub;
			
break;
		  
case "*":
			
$mult=$f*$s;
			
echo "Multiplication=".$mult;
			
break;
		  
case "/":
			
$div=$f/$s;
			
echo "Division=".$div;	
			
break;
		  
default:
			
echo "Invalid choice";
	
}
	
?>

<form method="post">
	
Enter first number<input type="text" name="f"/><hr/>
	
Enter second number<input type="text" name="s"/><hr/>
	
Enter your choice<input type="text" name="ch"/><hr/>
	
<input type="submit" value="Show Result"/>
  
</form>

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


Popular Tutorials

PHP Tutorial PHP Introduction For Beginners PHP Advantage PHP Software Requirement PHP WAMP Installation PHP XAMPP Installation PHP Syntax PHP Comments PHP Variables PHP $ and $$ Variables PHP Super global variables How to swap two numbers in PHP PHP Constant PHP:Magic Constant echo and print in PHP PHP Data Types PHP Form GET Method POST Method Form action PHP extract() Function PHP Display result in Textbox Multiple submit buttons php different actions Add two textbox values and display the result in third textbox PHP Operators PHP Arithmetic Operators PHP Assignment Operators PHP Comparative Operators PHP Logical Operators PHP Operators Precedence PHP Conditional Statement PHP if Statement PHP if-else Statement PHP if elseif else Statement PHP Switch Statement PHP calculator Profit and Loss What is Loop PHP For Loop Print star pattern in PHP Create table using for loop in PHP PHP While Loop PHP Do While Loop PHP Foreach Loop PHP String PHP String Functions PHP empty() function PHP str_split() Function PHP Numeric Functions PHP Tutorial PDF For Beginners PHP isset function PHP addcslashes() Function PHP addslashes() Function PHP bin2hex() Function PHP chop() Function PHP chr() Function PHP chunk_split() Function PHP convert_cyr_string() Function PHP convert_uudecode() Function PHP convert_uuencode() Function PHP count_chars() Function PHP crc32() Function PHP crypt() Function PHP echo() Function PHP explode() Function PHP fprintf() Function PHP get_html_translation_table() Function PHP hebrev() Function PHP hebrevc() Function PHP hex2bin() Function PHP html_entity_decode() Function PHP htmlentities() Function PHP htmlspecialchars() Function PHP htmlspecialchars_decode() Function PHP implode() Function PHP join() Function PHP lcfirst() Function PHP levenshtein() Function PHP localeconv() Function PHP ltrim() Function PHP md5() Function PHP md5_file() Function PHP metaphone() Function PHP money_format() Function PHP nl_langinfo() Function PHP nl2br() Function PHP number_format() Function PHP ord() Function PHP parse_str() Function PHP print() Function PHP printf() Function PHP quoted_printable_decode() Function PHP quoted_printable_encode() Function PHP quotemeta() Function PHP rtrim() Function PHP setlocale() Function PHP sha1() Function PHP sha1_file() Function PHP similar_text() Function PHP soundex() Function PHP sprintf() Function PHP sscanf() Function PHP str_getcsv() Function PHP str_ireplace() Function PHP str_pad() Function PHP str_repeat() Function PHP str_replace() Function PHP str_rot13() Function