Jump to content
Larry Ullman's Book Forums

Recommended Posts

I just started going through the book and ran into my first problem while working through the end of chapter 2 in the Pursue section:

 

Rewrite the gender conditional handle_form.php(Script 2.4) as one conditional instead of two nested ones.

 

The relevant part of Script 2.4 is:

if (isset($_POST['gender'])) {
        $gender = $_POST['gender'];
        if ($gender == 'M') {
            echo '<p><b>Good day, Sir!</b></p>';
        } elseif ($gender == 'F') {
            echo '<p><b>Good day, Madam!</b></p>';
        } else {
            $gender = NULL;
            echo '<p class="error"><b>Gender should be either M or F!</b></p>';
        }
    } else {
        $gender = NULL;
        echo '<p class="error"><b>You forgot to select your gender!</b></p>';
    }

I am using 'yes' and 'no' instead of 'M' and 'F' but this is the code that I used:

if(isset($_POST['newsletter']) == 'yes') {
        echo "<p>Thank you for signing up for our monthly newsletter!</p>";
    } elseif(isset($_POST['newsletter']) == 'no') {
        echo "<p>We are sorry you have decided NOT to sign up for our newsletter.</p>";
    } else {
        echo "<p>You for got to choose a newsletter option!</p>";
    }

I know the hint suggested that I use the AND operator. The above code seems like it should work but ifelse(or the 'no') is printing the same as the if(or the 'yes') response and the else(where nothing is checked) is printing the correct response. In other words, When no is checked on the form it is saying "thank you for signing up" instead of "sorry you have decided to NOT..."

 

Link to comment
Share on other sites

What you want to do is to check if $_POST['newsletter'] is set AND if the value of $_POST['newsletter'] is 'yes";

if that's not the case, you want to check if $_POST['newsletter'] is set AND if the value of $_POST['newsletter'] is 'no";

the final 'else' doesn't change.

 

I hope this helps,

 

Emilie

  • Upvote 1
Link to comment
Share on other sites

 Share

×
×
  • Create New...