Filed under: PHP
The Switch Statement
Use this if you have many codes to be executed and you want to execute only one.
Switch statement takes a single variable as input and then checks it against all different cases you set up for the switch statement then if a match was found then it executes the code otherwise if no match was found then the default case will be executed. Break is also important so that when a match is found, the statement will end right away and will not execute the remaining part of the statement.
Here is the syntax:
switch (variable)
{
case label1:
code to be executed if variable is equals to label1;
break;
case label2:
code to be executed if variable is equals to label2;
break;
default:
code to be executed if variable is not equals to label1 and label2;
}
Here is an example:
<html>
<body>
<?php
switch ($y)
{
case 1:
echo “y equals to 1″;
break;
case 2:
echo “y equals to 2″;
break;
case 3:
echo “y equals to 3″;
break;
default:
echo “y is not equals to 1, 2 or 3″;
}
?>
</body>
</html>
2 Comments so far
Leave a comment
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <pre> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>
cool, next time you need to paste formated code to anyone or a website try http://textsnip.com
Comment by jermaine March 2, 2008 @ 7:09 amthx 4 the tip!! =)..coz m just a newbie at this blogging thing hehe..il try that later..
Comment by fenix1987 March 2, 2008 @ 9:30 am