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 )

PHP code to write to a CSV file from MySQL query

Different versions of PHP - History and evolution of PHP

PHP code to import from CSV file to MySQL

Encrypting files using GnuPG (GPG) via PHP

PHP Warning: Unknown(): Unable to load dynamic library '/usr/local/php4/lib/php/extensions/no-debug ......

Decrypting files using GnuPG (GPG) via PHP

Send push notifications using Expo tokens in PHP

A Basic Example using PHP in AWS (Amazon Web Services)

Count occurrences of a character in a String in PHP

Password must include both numeric and alphabetic characters - Magento

Error: Length parameter must be greater than 0

Reading word by word from a file in PHP

Parent: child process exited with status 3221225477 -- Restarting

Convert a hex string into a 32-bit IEEE 754 float number in PHP

PHP file upload prompts authentication for anonymous users

Latest Articles (in PHP)