Switch syntax
If and Switch are very similar, but Switch is "prettier" and faster.
Published 15.08.2006 - Last edited 15.08.2006 - 10063 views - 0 comments
<?php
switch (variable)
{
case ´value1´:
# put code here (do this)
break;
case ´value2´:
# put code here (do that)
break;
default:
# put code here (do default)
break;
}
?>
Example:
<a href="index.php?page=1">Open page 1</a>
<a href="index.php?page=2">Open page 2</a>
<a href="index.php?page=3">Open page 3</a>
<?php
# The variable is page (see the links above)
# The values are given through the link (string)
switch (0)
{
case ´1´:
include ("1.inc.php");
break;
case ´2´:
include ("2.inc.php");
break;
case ´3´:
include ("3.inc.php");
break;
default:
include ("error.inc.php");
break;
}
?>
When clicking a link the selected value are handed to the script and if found it executes your case or default if not found. You can use this for page navigation shown in this example or any other situation where you have multiple choices depending on one variable. It is also possible to include a second Switch inside any of the cases above.
Grabbing remote content
Up one level
PHP Sniplets