Posted By:
9 Mar, 2014 12:44 am PST

How to write switch case control flow statement in PHP?

 How to write switch case control flow statement in PHP?

 If you want to make decision against many condition, so this case if or if—else or elseif is not suitable. In such situation we can use switch case.

Syntax :-

 

Switch(choice)

{

case label1 :

        // write your code here

         break;

 case label2 :

       // write your code here

       break;

case label3 :

        // write your code here

break;

default :

          // write your code here

}

Here choice is compared with each label. If it matches with any of the label then block belongs to that particular label gets executed. break is used to break control flow inside switch else it will move to next block of next case label and execute until break statement encountered else it reaches to end of switch.

Note: - two labels cannot have same value.

<?php

echo " <h2 > " ;

echo " Menu driven calculator for ADD , SUBTRACT , MULTIPY , DIVIDE two Numbers " ;

echo " <br > < br > " ;

echo "1 :ADD<br>”;

echo "2: SUBTRACT<br > " ;

echo "3 :MULTIPLY<br>”;

echo "4 :DIVIDE<br>”;

 

$num1 = rand (10 ,100) ;

 

// rand ( int min , int max ) this function returns a pseudo - random integer between

// " min " and " max " value .

$num2 = rand (10 ,100) ;

 

echo " Two number are <br > NUM1 = { $num1 } <br > NUM2 = { $num2 }←

<br > < br > " ;

$choice = rand (0 ,6) ;

echo " Random Choice is { $choice } <br > < br > " ;

switch ( $choice )// choice

{

case 1:// case 1

$add = $num1 + $num2 ;

echo " Addition of { $num1 } and { $num2 } is { $add } " ;

 

break ;

case 2:// case 2

$sub = $num1 - $num2 ;

echo " Subtraction of { $num1 } and { $num2 } is { $sub } " ;

break ;

case 3:// case 3

$mul = $num1 * $num2 ;

echo " Multiplication of { $num1 } and { $num2 } is { $mul }";

break ;

case 4:// case 4

$div = $num1 / $num2 ;

echo " Division of { $num1 } and { $num2 } is { $div } " ;

break ;

default : // default case

echo " Wrong Choice " ;

}

?>

                                                       SwitchCase.php

SwitchCase Output

Attachment: SwitchCase.php


How to write switch in PHP

 

Switch is used to select one of many blocks in the code.User will select block accordingly and that particular block will be executed.

 

//To print Subject names using switch in PHP

<!DOCTYPE html>

<html>

<body>

<?php

$subject="Science";

switch ($subject)

{

case "Maths":

  echo "You selected Maths";

  break;

case "English":

  echo "You selected English!";

  break;

case "Science":

  echo "You selected Science!";

  break;

default:

  echo "You did not select any subject!!!";

}

?>

</body>

</html>

 

/*Output of the above program is:

You selected Science!

*/

 

Attachment: switch.php
Was it useful?  




Please login to reply to this problem.