The question is taken from http://www.programmr.com/node/137861/begin and you can test it there.
I am writing a program which displays an appropriate name for a person, using a combination of nested if's and compound conditions. Ask the user for a gender, first name, last name and age.
If the person is female and 20 or over, ask if she is married. If so, display "Mrs." in front of her name. If not, display "Ms." in front of her name. If the female is under 20, display her first and last name.
If the person is male and 20 or over, display "Mr." in front of his name. Otherwise, display his first and last name.
Note that asking a person if they are married should only be done if they are female and 20 or older.
Here is my code:
<?php
$finalName;
echo "What is your Gender (M or F):";
$gender = trim(fgets(STDIN));
echo "First Name:";
$firstName = trim(fgets(STDIN));
echo "Last Name:";
$lastName = trim(fgets(STDIN));
echo "Age:";
$age = trim(fgets(STDIN));
if ($gender == "M" and $age>19) {
$finalName = "Mr. ".$lastName;
}
if ($age<20) {
$finalName = $firstName.$lastName;
}
if ($gender == "F" and $age>19) {
echo "Are you married:";
$married = trim(fgets(STDIN));
if ($married == "Y") {
$finalName = "Mrs. ".$lastName;
}
else {
$finalName = "Ms. ".$lastName;
}
}
echo "Then I will call you ".$finalName;
exit;
?>
The code does not give expected output. Is there something wrong in the logic or does if statement not work this way ?