Home > DeveloperSection > Articles > PHP Switch Statement

PHP Switch Statement

Posted by  Arun Singh
on    September-07-2011 18:03 PM

PHP PHP 
Ratings:
0 Comment(s)
 1411  View(s)
Rate this:

PHP Switch Statement

‘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
















Recent Activities


Kamlakar Singh added new Blog Convert Text Document to PDF File   11 days ago

Kamlakar Singh added new Article Introduction to Backbone.js   11 days ago

Kamlakar Singh added new Question Explain the AdRotator Control.   11 days ago

Don't want to miss updates? Please click the below button!