Confused in the use of if and else if- Save the farm PHP Project

https://www.codecademy.com/courses/learn-php/projects/save-the-farm

I am confused in the use of if and else if. This particular lesson on #4, it makes clear that it is better to have 2 ifs statements because the player can have both:

If the player is wearing contacts, you should print "You are wearing contacts.\n" .
If the player is wearing glasses, you should print "You are wearing glasses.\n" .

This makes perfect sense to me. But:
Later for lesson #14, it shows that if and elseif statements should be used. I don’t see why one can’t use only IFs statements. This is what they recommend:

function changeLocation(){
    global $location;
    echo "Where do you want to go?\n";
     $go_to = readline (">> ");
     $go_to = strtolower($go_to);
     echo "\n";
      if ($location === "kitchen" && $go_to==="bathroom"){
        echo "You go to: $go_to.\n";
        $location = $go_to;
      } elseif ($location === "kitchen" && $go_to === "woods"){
        echo "You follow the winding path, shivering as you make your way deep into the Terror Woods.";
        $location = $go_to;
      } elseif ($location === "bathroom" && $go_to === "kitchen"){
        echo "You go to: $go_to.\n";
        $location = $go_to;
      } elseif ($location === "woods" && $go_to === "kitchen"){
        echo "You go to: $go_to.\n";
        $location = $go_to;
      } elseif ($go_to === "woods" || $go_to === "kitchen"|| $go_to === "bathroom"){
         echo "You can't go directly to $go_to. Try going somewhere else first.\n";
      } else {
        echo "That doesn't make sense. Are you confused? Try 'look around'.\n";
      }
}

Why isn’t using IFs statement only (except for the last one) correct here? It seems like you will never get two statements printed out because the user inputs 1 place where they want to go. And that place will get compared with the $location. And if a user writes the wrong thing, then it will print out the else statement. I’m sure the code will work with only If’s except the last statement, but is there any place where i can read or understand what is the best practice for someone who is new to PHP? Thanks.

Hello, @script0131595176.

If you use a series of if statements instead of the if...elseif...else structure, every if statement has to be evaluated when your program runs. In the if...elseif...else structure, once a condition is true, control will be passed to the line of code following the else block. It is more efficient. In the 2nd example you posted, there is no need to check all of the remaining possibilities once one of the conditions evaluates to true. In your first example with the glasses and contacts, there is a reason to test both conditions, so an if statement for each is appropriate. If you haven’t already, you’ll soon learn about the switch statement which is another way to handle multiple possibilities.

2 Likes

Now that makes things a whole lot clearer. I see the key is efficient. So it’s not that only ifs statements can’t be used, but that there is no need to check all of them. Many thanks. I did do Switch already. But my understanding is that you can only have one condition. For example:

switch ($location) {
case “bathroom”:
do something;
break;
case “kitchen”:
do something;
break;
}

I wonder if you can do this:

switch ($location, $go_to) {
case “bathroom” && case “kitchen” :
do something;
break;
case “kitchen” && case “woods”:
do something;
break;
}
How would one format it correctly to be able to add two conditionals? Thanks.

1 Like

Well, there’s a way to do it, but there’s nothing wrong with using the if...elseif...else structure. Here’s a generic example of how you could use switch:

$location = "office";
$go_to = "lobby";

switch(TRUE) { //by using TRUE the matching case will be the one that evaluates to TRUE
  case $location === "break room" && $go_to === "lobby": //evaluates to FALSE
    echo "Hello!";
    break;
  case $location === "office" && $go_to === "lobby": //evaluates to TRUE
    echo "Bye!";
    break;
  default:
    echo "Huh?";
}
//output: Bye!

Oh this is amazing. It gives me a lot of leeway to think of switch statements. Thanks.

1 Like

But moving on with the IFs statements. I just encounter an issue on that same url #25 where it recommends:

You should declare a variable $ready_to_work to decide if the player is prepared to move the cupboard. $ready_to_work should be TRUE if they player is not hungry and they’re wearing contacts and they are not wearing glasses and they do not need to pee.

There’s:
$ready_to_work = !$is_hungry && $wearing_contacts && !$wearing_glasses && !$needs_to_pee;

My code is:
if ((!$is_hungry) && $wearing_contacts && (!$wearing_glasses) && (!$needs_to_pee)){
$ready_to_work=TRUE;
}

My 1st question is: what will $ready_to_work have? Is it going to have an array with True and False values? or just one True or one False value?

My 2nd question is: Why didn’t the lesson use the IF statement? I could be wrong, but my statement also accomplishes the same thing, which is to get $ready_to_work to be TRUE. Please explain. Thanks.

$ready_to_work will be assigned either TRUE or FALSE. That value is determined by the truthiness of the expression on the right side of the = operator in their example. Since the expression is using the logical operator &&, every boolean value in the expression must be TRUE for the expression to evaluate to TRUE. The method they used is more efficient than using the if statement. The expression whether as the condition of an if statement or as the value to be assigned (as in their example) will be evaluated, and return a single TRUE or FALSE value. Both methods accomplish the exact same task. There’s requires one less step.
Consider this code:

//assign $ans using an if ... else block
if(5 === 3) {
  $ans = TRUE;
} else {
  $ans = FALSE;
}
echo $ans ? "5 equals 3? Oh no! Someone broke math!\n" : "5 does not equal 3.\n"; 

//versus:
//assign $ans in a single line
$ans = !(5 === 3);
echo $ans ? "5 equals 3? Oh no! Someone broke math!\n" : "5 does not equal 3.\n";

//In most languages you can print bool values. They appear as either True, False, (capitalization varies)
//or 1, 0 depending on the language. php is a bit quirky. It will print 1 for TRUE, but nothing for FALSE:
echo TRUE, " <--Should be a 1 here.\n";
echo FALSE, " <--See. Nothing.";

Output:

5 does not equal 3.
5 equals 3? Oh no! Someone broke math!
1 <–Should be a 1 here.
<–See. Nothing.

If you are unfamiliar with the ternary operators (? :), it’s a shorthand way of using a simple if ... else.

Yes i am very familiar with ternary operators. I have done that lesson and seems straight forward. Thanks for explaining it.

https://www.codecademy.com/courses/learn-php/lessons/introduction-to-php-form-validation/exercises/custom-validations?action=resume_content_item

Throughout my journey in conditionals, i have stumble upon another situation.

The solution for this lesson is:

if ($card_type === “mastercard”){
if (preg_match("/5[1-5][0-9]{14}/", $card_num) === 1){
$feedback = $success_message;
} else {
$feedback = $error_message;
}
} else if ($card_type === “visa”) {
if (preg_match("/4[0-9]{12}([0-9]{3})?([0-9]{3})?/", $card_num) === 1){
$feedback = $success_message;
} else {
$feedback = $error_message;
}

My question is where did the ===1 came from?

It doesn’t explain it in the lesson or mentions a 1 at all. I understand what the rest of the statement is, except THAT ===1. I know it checks to see if it is a mastercard or visa. If mastercard, it checks for the patterns. If pattern is okay, then $success_message. If not, $error_message. But how does 1 fit into this? Is it like 1 =True and 0= False kind of thing? Thanks in advance and very appreciated.