PHP Switch Function
By Brian on Nov 16, 2009 with Comments 13
The function switch() in PHP is used to execute different codes based on a variable’s value. This is used in place of the IF/ELSE IF statements. A default value is optional and, if specified, is used when no other option is matched. You must include a break; after each case or the following cases will all return true.
<?php
switch($var){
case "blue":
echo "You have selected the color blue.";
break;
case "green":
echo "You have selected the color green.";
break;
case "red":
echo "You have selected the color red.";
break;
case "yellow":
echo "You have selected the color yellow.";
break;
default:
echo "You have not chosen a color.";
}
?>
You can use this with forms and such to determine an action based on a submitted value as well! Here is an example using the switch() function in a form:
<form action="submit.php" method="post"> Select your gender: <select name="gender"> <option value="">Select one...</option> <option value="male">Male</option> <option value="female">Female</option></select> <input type="submit" name="submit" value="Submit" /> </form>
Now on our PHP side of the script (submit.php) we will use the switch() function to evaluate the value.
<?php
// submit.php
if($_POST['submit']){
$value = $_POST['gender'];
switch($value){
case "male":
echo "You are male. Thank you.";
break;
case "female":
echo "You are female. Thank you.";
break;
default:
echo "Please choose your gender.";
}
}
?>
Popularity: 3% [?]
Filed Under: PHP • Web Programming

Nice article.
very good blog!.. awesome templates as well !
Great text and nice blog.
I was just having a conversation over this I am glad I came across this it cleared some of the questions I had.
I stumbled across your blog and think it’s fantastic, keep us posting
I was bored until i’ve found your blog, interesting posts
I’ve just started off a blog, the knowledge you give on this site has aided me extremely. Thank you for all your time & work.
Thanks for this great blog.
Thanks for this article, it was great to read.
Very good article. Coherent and informative just like a good article should be. I’ll definitively be back for more.
The great summary assited me a lot! Saved the blog, extremely interesting categories everywhere that I read here! I really like the info, thank you.
A good friend of mine visits your blog quite often and recommended it to me to read too. The writing style is solid and the content is pertinent. Many thanks for the insight you provide the readers!
This nice summary encouraged me very much! Bookmarked the blog, extremely excellent topics just about everywhere that I see here! I appreciate the info, thank you.