PHP Switch Statement
The Switch statement in PHP is used to perform one of several different
actions based on one of several different conditions.
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
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
<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>
|
|
|
Get Your Diploma!
W3Schools' Online Certification Program is the perfect solution for busy
professionals who need to balance work, family, and career building.
The HTML Certificate is for developers who want to document their knowledge of HTML, XHTML, and CSS.
The JavaScript Certificate is for developers who want to document their knowledge of JavaScript and the HTML DOM.
The XML Certificate is for developers who want to document their knowledge of XML, XML DOM and XSLT.
The ASP Certificate is for developers who want to document their knowledge of ASP, SQL, and ADO.
The PHP Certificate is for developers who want to document their knowledge of PHP and SQL (MySQL).
|
|