Switch Statements

   

In the C programming language, switch statement support arose out of the need for a little something extra when doing if/then types of computation. With the if/then statement, you are locked into a single condition. Switch statements allow for additional evaluations of the data, even though one of the cases may have been met. Switch statements can also save you from typing many if/elseif/elseif/… statements. PHP follows C's use of switch statements.

 $a = "100";  switch($a) {     case(10):       echo "The value is 10";       break;     case (100):       echo "The value is 100<br>";     case (1000):       echo "The value is 1000";       break;     default:       echo "<p>Are you sure you entered a number?"; } 

As you can see, switch statements have four basic parts:

  • The switch The switch identifies what value or expression is going to be evaluated in each of the cases. In the example above, you tell the switch statement that you are going to evaluate the variable $a in the subsequent cases.

  • The case The case statement evaluates the variable you passed from the switch command. You can use case() the same way you'd use an if statement. If the case holds true, then everything after the case statement is executed, until the parser encounters a break command, at which point execution stops and the switch is exited.

  • Breakpoints Defined by the break command, exit the parser from the switch. Breakpoints are normally put after statements executed when a case() is met.

  • Default The default is a special kind of case. It is executed if none of the other case statements in the switch have been executed.


   
Top


Advanced PHP for Web Professionals
Advanced PHP for Web Professionals
ISBN: 0130085391
EAN: 2147483647
Year: 2005
Pages: 92

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net