Programming Tutorials

switch Statements in PHP

By: Andi, Stig and Derick in PHP Tutorials on 2008-11-22  

You can use the switch construct to elegantly replace certain lengthy if/ elseif constructs. It is given an expression and compares it to all possible case expressions listed in its body. When there's a successful match, the following code is executed, ignoring any further case lines (execution does not stop when the next case is reached). The match is done internally using the regular equality operator (==), not the identical operator (===). You can use the break statement to end execution and skip to the code following the switch construct.

Usually, break statements appear at the end of a case statement list, although it is not mandatory. If no case expression is met and the switch construct contains default, the default statement list is executed. Note that the default case must appear last in the list of cases or not appear at all:

switch ($answer) {
case 'y':
case 'Y':
  print "The answer was yes\n";
break;
case 'n':
case 'N':
  print "The answer was no\n";
break;
default:
  print "Error: $answer is not a valid answer\n";
break;
}
Statement Statement List

switch (expr){

case expr:

statement list

case expr:

statement list

...

default:

statement list

}

switch (expr):

case expr:

statement list

case expr:

statement list

...

default:

statement list

endswitch;






Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in PHP )

Latest Articles (in PHP)