DJ Mike's Tutorials: PHP


< ^ >

Conditional Statements

Switch Statement

A switch statement is something like an if statement in that it it controls how the program flow based on conditions but there are some key Differences. When you use an if statement with an else statement, you can test different conditions; with switch, you only test one. The result of the condition being evaluated by an if statement is read as true or false; with switch, the results can be any number of values. A switch statement is best when you are testing a single condition that has many possible values. The syntax is:

<?
switch ( test_expression )
{
case 
"value_01":
# Code block 01
break;
case 
"value_02":
# Code block 02
break;
# more posible results
default:
# Code block if there is no match
}
?>

Note that that is a colon after the case values, not a simicolon. The break; statement breaks you out of the switch statement. If you don't have a break; for a case, PHP will continue on to the next case after it executes the code for the first case. default is a block of code to be executed if the result of your test expression does not match any case.

The example below tests the input of a form for ten possible values, outputs different results debendig on the value and has a default output if there is no match for your list of possible values

Show Code | Show Working Example
Show Code | Show Working Example



< ^ >



Created by DJ Mike from Santa Barbara

DJ Mike


Dance Away Santa Barbara's Home Page
<a href="http://www.statcounter.com/" target="_blank"> <img src="http://c5.statcounter.com/counter.php?sc_project=1321035&java=0&security=da2193dc" alt="counter free hit invisible" border="0" /></a>