Page 60 - Open Soource Technologies 304.indd
P. 60

Web Technologies-I



                   Notes
                                 switch ($myState) {

                                   case “In”:
                                     echo “You are from India”;
                                     break;
                                   case “VT”:
                                     echo “You are from Vermont”;
                                     break;
                                   case “MA”:

                                     echo “You are from Massachussetts”;
                                     break;
                                   default:
                                     echo “You are not from around here”;
                                     break;
                                   }
                                 Let us look at the various elements.

                                 Case Statement
                                 The case keyword is a label; it marks a point in the code to do something. Specifically it marks
                                 the point in the code to begin executing statements if the value of the expression being evaluated
                                 by the switch statement is equal to the value immediately following the case keyword or if the
                                 expression following the case keyword evaluates to true. The colon marks the end of the label.
                                 The entire label should be on one line.

                                 In PHP, the case statement takes an expression which must equate to true for the following code
                                 to be run. If you are doing simple equality then you can just provide the value you are checking
                                 for and it assumes that the expression is testing the switch expression against the value in question
                                 for equality. However, by allowing expressions, you can also test for other conditions, such as
                                 greater than and less than relationships. When using expressions, the expression you are testing
                                 against must be repeated in the case statement.


                                   switch ($someNumber) {
                                     case 0:
                                     echo “Zero is not a valid value.”;
                                     break;
                                   case $someNumber < 0:
                                     echo “I cannot use negative numbers.”;

                                     break;
                                   default:
                                     echo “Ready to compute.”;
                                     break;
                                   }



        54                                LOVELY PROFESSIONAL UNIVERSITY
   55   56   57   58   59   60   61   62   63   64   65