Home » Featured, PHP Tutorials, Tutorials

PHP and switch Conditional Statements

4 March 2009 185 views No Comment


So we learned briefly about if, else and elseif conditionals and in the next example we will be talking about switch conditionals. So what is switch conditional? Basically a switch conditional is used to shorten up code if you have a lot of elseif statements by taking one possible condition and running it through.

So what the switch condition example I will do is shorten up this:

if ($_POST['color'] == 'red') {
	print '<p style="color:red;">Red is your favorite color.</p>';
} elseif ($_POST['color'] == 'yellow') {
	print '<p style="color:yellow;">Yellow is your favorite color.</p>';
} elseif ($_POST['color'] == 'green') {
	print '<p style="color:green;">Green is your favorite color.</p>';
} elseif ($_POST['color'] == 'blue') {
	print '<p style="color:blue;">Blue is your favorite color.</p>';
} else { // Problem!
	print '<p class="error">Please select your favorite color.</p>';
	$okay = FALSE;
}

So by using a switch conditional to replace a bunch of elseif conditions it will look a bit cleaner and a bit smaller

// Validate the color:
switch ($_POST['color']) {
	case 'red':
		print '<p style="color:red;">Red is your favorite color.</p>';
		break;
	case 'yellow':
		print '<p style="color:yellow;">Yellow is your favorite color.</p>';
		break;
	case 'green':
		print '<p style="color:green;">Green is your favorite color.</p>';
		break;
	case 'blue':
		print '<p style="color:blue;">Blue is your favorite color.</p>';
		break;
	default:
		print '<p class="error">Please select your favorite color.</p>';
		$okay = FALSE;
		break;
} // End of switch.

So what is happening in this PHP snippet?

First is case and case is used to identify your variable and in this case the first one would be red, and so once the switch identifies case it will display that specific variable. Now the script will keep on running until it either A) hits the conditional statement or B) detects a break statement. As for what a break statement is, a break statement pretty much ends the switch from cycling through again and thus creating a indefinite loop and making the script run forever with no end in site or odds are produce PHP errors when running the script.

body {
	font-family:"Lucida Grande", "Lucida Sans Unicode", Verdana, Arial, Helvetica, sans-serif;
}
p, h1, form, button {
	border:0;
	margin:0;
	padding:0;
}
.spacer {
	clear:both;
	height:1px;
}
/* ----------- My Form ----------- */
.myform {
	margin:0 auto;
	width:400px;
	height:400px;
	padding:14px;
}
/* ----------- stylized ----------- */
#stylized {
	border:solid 2px #b7ddf2;
	background:#ebf4fb;
}
#stylized h1 {
	font-size:14px;
	font-weight:bold;
	margin-bottom:8px;
}
#stylized p {
	font-size:11px;
	color:#666666;
	margin-bottom:20px;
	border-bottom:solid 1px #b7ddf2;
	padding-bottom:10px;
}
#stylized label {
	display:block;
	font-weight:bold;
	text-align:right;
	width:140px;
	float:left;
}
#stylized .small {
	color:#666666;
	display:block;
	font-size:11px;
	font-weight:normal;
	text-align:right;
	width:140px;
}
#stylized input {
	float:left;
	font-size:12px;
	padding:4px 2px;
	border:solid 1px #aacfe4;
	width:200px;
	margin:2px 0 20px 10px;
}
#stylized select {
	float:left;
	font-size:12px;
	padding:4px 0px;
	border:solid 1px #aacfe4;
	width:200px;
	margin:2px 0 20px 10px;
}
#stylized button {
	clear:both;
	margin-left:150px;
	width:125px;
	height:31px;
 background:#666666 text-align:center;
	line-height:31px;
	color:#FFFFFF;
	font-size:11px;
	font-weight:bold;
}
<div style="width:450px;">Please complete this form to register:
  <div style="width:450px;">
    <div id="stylized" class="myform">
  <form action="script_06_02.php" method="post">

    <label>Email Address:<span class="small">Enter Email</span></label>
    <input type="text" name="email" size="30" />

    <label>Password:<span class="small">Enter Password</span></label>
    <input type="password" name="password" size="20" />

    <label>Password:<span class="small">Confirm Password</span></label>
    <input type="password" name="confirm" size="20" />

    <label>Date Of Birth:<span class="small">Enter Month, Day, Year</span> </label>
    <select name="month">
      <option value="">Month</option>
      <option value="1">January</option>
      <option value="2">February</option>
      <option value="3">March</option>
      <option value="4">April</option>
      <option value="5">May</option>
      <option value="6">June</option>
      <option value="7">July</option>
      <option value="8">August</option>
      <option value="9">September</option>
      <option value="10">October</option>
      <option value="11">November</option>
      <option value="12">December</option>
      </select>
    <label>Day: <span class="small">Enter Month, Day, Year</span></label>
    <select name="day">
      <option value="">Day</option>
      <option value="1">1</option>
      <option value="2">2</option>
      <option value="3">3</option>
      <option value="4">4</option>
      <option value="5">5</option>
      <option value="6">6</option>
      <option value="7">7</option>
      <option value="8">8</option>
      <option value="9">9</option>
      <option value="10">10</option>
      <option value="11">11</option>
      <option value="12">12</option>
      <option value="13">13</option>
      <option value="14">14</option>
      <option value="15">15</option>
      <option value="16">16</option>
      <option value="17">17</option>
      <option value="18">18</option>
      <option value="19">19</option>
      <option value="20">20</option>
      <option value="21">21</option>
      <option value="22">22</option>
      <option value="23">23</option>
      <option value="24">24</option>
      <option value="25">25</option>
      <option value="26">26</option>
      <option value="27">27</option>
      <option value="28">28</option>
      <option value="29">29</option>
      <option value="30">30</option>
      <option value="31">31</option>
      </select>
    <label>Year:<span class="small">Enter Month, Day, Year</span></label>
    <input type="text" name="year" value="YYYY" size="4" />

    <label>Favorite Color:<span class="small">Pick Favorite Color</span> </label>
    <select name="color">
      <option value="">Pick One</option>
      <option value="red">Red</option>
      <option value="yellow">Yellow</option>
      <option value="green">Green</option>
      <option value="blue">Blue</option>
      </select>

    <input type="submit" name="submit" value="Register" />

  </form>
  </div>
  </div>
</div>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
	"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
	<title>Registration</title>
	<style type="text/css" media="screen">
		.error { color: red; }
	</style>
</head>
<body>
<h2>Registration Results</h2>

Full PHP script that includes if, else, switch conditional statements

// Flag variable to track success:
$okay = TRUE;

// Validate the email address:
if (empty($_POST['email'])) {
	print '<p class="error">Please enter your email address.</p>';
	$okay = FALSE;
}

// Validate the password:
if (empty($_POST['password'])) {
	print '<p class="error">Please enter your password.</p>';
	$okay = FALSE;
}

// Check the two passwords for equality:
if ($_POST['password'] != $_POST['confirm']) {
	print '<p class="error">Your confirmed password does not match the original password.</p>';
	$okay = FALSE;
}

// Validate the birthday:
$birthday = '';

// Validate the month:
if (is_numeric($_POST['month'])) {
	$birthday = $_POST['month'] . '-';
} else {
	print '<p class="error">Please select the month you were born.</p>';
	$okay = FALSE;
}

// Validate the day:
if (is_numeric($_POST['day'])) {
	$birthday .= $_POST['day'] . '-';
} else {
	print '<p class="error">Please select the day you were born.</p>';
	$okay = FALSE;
}

// Validate the year:
if ( is_numeric($_POST['year']) AND (strlen($_POST['year']) == 4) ) {

	// Check that they were born before 2009.
	if ($_POST['year'] >= 2009) {
		print '<p class="error">Either you entered your birth year wrong or you come from the future!</p>';
		$okay = FALSE;
	} else {
		$birthday .= $_POST['year'];
	} // End of 2nd conditional.

} else { // Else for 1st conditional.

	print '<p class="error">Please enter the year you were born as four digits.</p>';
	$okay = FALSE;

} // End of 1st conditional.

// Validate the color:
switch ($_POST['color']) {
	case 'red':
		print '<p style="color:red;">Red is your favorite color.</p>';
		break;
	case 'yellow':
		print '<p style="color:yellow;">Yellow is your favorite color.</p>';
		break;
	case 'green':
		print '<p style="color:green;">Green is your favorite color.</p>';
		break;
	case 'blue':
		print '<p style="color:blue;">Blue is your favorite color.</p>';
		break;
	default:
		print '<p class="error">Please select your favorite color.</p>';
		$okay = FALSE;
		break;
} // End of switch.

// If there were no errors, print a success message:
if ($okay) {
	print '<p>You have been successfully registered (but not really).</p>';
	print "<p>You entered your birthday as $birthday.</p>";
}
</body>
</html>

Hopefully my explanation of using a switch conditional makes sense, of course I implore for those who read this to read more about it and read tutorials about it as well to get a stronger understand of this. Now that you have a basic idea what if, elseif and switch conditionals are like, and so it is just a matter of making sure you have strong background in setting these up and thus making life easier when you code.

So try out the examples and it should run perfectly once you fill everything out and it should also produce errors if you don’t fill everything out.


Leave your response!

You must be logged in to post a comment.