Jump to content
Larry Ullman's Book Forums
MelissaMMDP

Chapter 2 Pursue - bullet 3 rewrite gender conditional

Recommended Posts

I've been struggling with the following Pursue challenge. I found an eloquent solution in the forum for version 4 but it included a function which will not be discussed until chapter 3.  I just can't find a way to echo a greeting based on gender selection without a nested conditional. I would appreciate help on this.

Pursue:

Rewrite the gender conditional in handle_form.php (Script 2.4) as one conditional instead of two nested ones. Hint: You’ll need to use the AND operator. 

Here is the nested conditional:

   // Validate the gender:
   if (isset($_POST['gender'])) {

      $gender = $_POST['gender'];

      if ($gender == 'M') {
         $greeting = '<p><strong>Good day,
         Sir!</strong></p>';
      } elseif ($gender == 'F') {
         $greeting = '<p><strong>Good day,
         Madam!</strong></p>';
      } else { // Unacceptable value.
         $gender = NULL;
         echo '<p class="error">Gender
         should be either "M" or "F"!
         </p>';
      }

   } else { // $_POST['gender'] is not set.
      $gender = NULL;
      echo '<p class="error">You forgot to
      select your gender!</p>';
   }

Edited by MelissaMMDP

Share this post


Link to post
Share on other sites

Answered my own question:

   // Validate the gender:
   $gender = $_REQUEST['gender'] ?? NULL;

   if ($gender == 'M') {
         $greeting = '<p><strong>Good day, Sir!</strong></p>';
      } elseif ($gender == 'F') {
        $greeting = '<p><strong>Good day, Madam!</strong></p>';
      } else { // $_POST['gender'] is not set.
        echo '<p class="error">You forgot to select your gender!</p>';
      }

Share this post


Link to post
Share on other sites

That's a fine solution! In the other thread I posted what I originally had in mind, though. With programming, there are many ways!

  • Like 1

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...

×
×
  • Create New...