articles

Home / DeveloperSection / Articles / PHP Switch Statement

PHP Switch Statement

Anonymous User5900 07-Sep-2011

‘Switch’ statement is conditional statement used to perform different action based on different condition. I.e. switch statement is used to select one of many blocks of code to be executed.

The switch statement is a control statement that handles multiple selections by passing control to one of the case statements within its body.

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.

Syntax:
switch (expression)
        {
           caselabel_1:
           codetobeexecutedifexpression=label_1 ;
           break;
           caselabel_2:
           codetobeexecutedifexpression=label_2;
           break;
           .............
           .............
 
           default:
           codetobeexecutedifexpressionisnotequaltoalllabel_1, label_2,... etc.
         
        }

 

Let’s we have an example, how to implement switch statement in PHP.

Example:
<html>
<head>
       <title> Switch Statement</title>
       </head>
<body>
       <?php
              // Declare a variable which is stores product name
              $product_Name = "Mouse";
 
              switch (    $product_Name )
                {
                     case "Monitor" :
                           echo "This is monitor section";
                           break;
                     case "Keyboard" :
                           echo "This is Keyboard section";
                           break;
                     case "CPU" :
                           echo "This is CPU section";
                           break;
                     case "Mouse" :
                           echo "This is mouse section";
                           break;
                     default:
                     echo "All above block of code not executed this is default section";
                }
       ?>
</body>
 
</html>
Desired Output:

PHP Switch Statement



Updated 07-Sep-2019
I am a content writter !

Leave Comment

Comments

Liked By