PHP Switch Statement

kane

194.***.***.***
1,451 days ago

PHP Switch Statement

The Switch Statement

If you want to select one of many blocks of code to be executed, use the Switch statement.

The switch statement is used to avoid long blocks of if..elseif..else code.
Syntax

Code:

switch (expression)
{
case label1:
code to be executed if expression = label1;
break;
case label2:
code to be executed if expression = label2;
break;
default:
code to be executed
if expression is different
from both label1 and label2;
}


Example

This is how it works:

* A single expression (most often a variable) is evaluated once
* The value of the expression is compared with the values for each case in the structure
* If there is a match, the code associated with that case is executed
* After a code is executed, break is used to stop the code from running into the next case
* The default statement is used if none of the cases are true

Code:


<html>
<body>

<?php
switch ($x)
{
case 1:
echo "Number 1";
break;
case 2:
echo "Number 2";
break;
case 3:
echo "Number 3";
break;
default:
echo "No number between 1 and 3";
}
?>

</body>
</html>

Ogilvy

80.***.***.***
1,450 days ago
As much as I dislike messy code, I never did get into using this. You know what they say about habbits. :)

stalemate

202.***.***.***
1,449 days ago
This code is excellent as it has reduced the lengthy code.I will surely use it in every of my program.

penguinmama

12.***.***.***
1,447 days ago
Can this be used as a counterpart to perl's CASE to reuse the same script? and if so, how does one access the "action" inside the php file?