Working with Conditions - Exercise

Contact Us or call 1-877-932-8228
Working with Conditions - Exercise

Working with Conditions

Duration: 20 to 30 minutes.

In this exercise, you will create a page for handling a simple form submission.

  1. Open FlowControl/Exercises/Greeting.html in your editor and review the code. This is the form that will be submitted. Filled out, it looks like this:Greeting Form This form is submitted using the get method, which means the form entries will be appended to the query string and will be accessible in the $_GET array.
    HTML forms will be discussed more later in the course.
  2. Open FlowControl/Exercises/Greeting.php in your editor.
  3. Insert a PHP block that checks to see if the user filled out both the LastName and the Gender fields in the form.
    • If the user failed to fill out either one of the fields, write out an error message to the screen.
    • If the user filled out both fields, return a gender-appropriate greeting such as "Hello Mr. Dunn!" or "Hello Ms. Dunn!" If the gender is not recognizable (e.g, not male or female), return an error message.
  4. Try to use both an if condition and a switch statement in this exercise.
  5. When you are done, test your solution in your browser.

Challenge

It is likely that your solution does not take into account different cases for the gender. For example, "MALE" and "FEMALE" may not be recognized as valid genders. Try to find the function at http://www.php.net that can be used for converting the user's entry to all lowercase letters and use that function to make the gender check case insensitive.

Solution:

FlowControl/Solutions/Greeting.php
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Greeting Page</title>
</head>
<body>
<?php
	$lastName = $_GET['LastName'];
	$gender = $_GET['Gender'];
	
	if ($lastName == '' || $gender == '')
	{
		echo 'Error: You must fill out the form.
				Please <a href="Greeting.html">try again</a>.';
	}
	else
	{
		switch($gender)
		{
			case 'male' :
				echo "Hello Mr. $lastName!";
				break;
			case 'female' :
				echo "Hello Ms. $lastName!";
				break;
			default :
				echo "<b>$gender</b> is not a gender!";
		}
	}
?>
</body>
</html>

Challenge Solution:

FlowControl/Solutions/Greeting-challenge.php
---- C O D E   O M I T T E D ----

		switch(strtolower($gender))
		{
			case 'male' :
				echo "Hello Mr. $lastName!";
				break;
			case 'female' :
				echo "Hello Ms. $lastName!";
				break;
			default :
				echo "<b>$gender</b> is not a gender!";
		}
---- C O D E   O M I T T E D ----
Next