Home » Code, PHP Functions

PHP Switch Function

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.";

}

}

?>
0

Popularity: 4% [?]

Share/Bookmark this!

12 Comments

Leave a reply

Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

This is a Gravatar-enabled weblog. To get your own globally recognized avatar, please register at Gravatar.

Side Notes

This entry was posted by on November 16, 2009 at 7:07 PM and filed under Code, PHP Functions category.

You can add your comments or trackback from your own site. To keep you updated to the latest discussion, you can subscribe to these comments via RSS.

Recent Entries

Pages

Recent Comments

Resources

Questions & Answers

Just started! Have not answered any questions.

Tag Cloud

background body CSS database date dropdown email error_reporting favicon file filesize form format function global hosting HTML image Javascript limit link linkbar mysql numbers online option ordinalize pagination pattern photoshop PHP resize rows script search snowing stylesheet switch table thumbnail time timestamp upload validate variables

Sponsors