Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP PHP Arrays and Control Structures PHP Conditionals Conditionals

PHP Arrays and Control Structures Quiz - I am in the conditionals quiz and am unsure why my answer is wrong.

Here's the question: What will be displayed when the following block of code is executed? All comments are added by me.

$username = "Treehouse"; //This evaluates to true //so this first if statement executes if ($username) { if ($username != "Treehouse") { //$username == "Treehouse" so this block should be skipped echo "Hello $username"; } } else { //This block should be executed echo "You must be logged in"; }

Comments show my thought process but "You must be logged in" was marked incorrect and it said the username evaluates to true in the first conditional...which is true..but the second conditional does not.

2 Answers

I added some notes to try to explain the flow. Hope it make sense.

<?php
$username = "Treehouse";
if ($username) { // true
    if ($username != "Treehouse") { // username DOES equal Treehouse. Not executed
        echo "Hello $username";
    }
// flow 'ends' here
} else { // because the username is true, this isnt executed
    echo "You must be logged in";
}

// so nothing happens
Alexander Nygaard
Alexander Nygaard
988 Points

I don't understand the logic behind this.

<?php
$username = "Treehouse";
if ($username) { // This is true. So in this case, proceed to next if statement.
    if ($username != "Treehouse") { // Is the username NOT 'Treehouse'? It is, so skip the 'echo'.
        echo "Hello $username"; // Ignored.
    }
} else { // First IF is true, but the second IF is NOT true. So proceed to 'echo', or is that not the case?
    echo "You must be logged in"; // I originally assumed that both IF statements had to be true, but as I am typing this, I realized that if one is true and one is false, the flow SHOULD indeed end where richporter pointed it out.
}

I think I understand it now, just had to try to explain my own mindset. I'll leave the reply so I can get a confirmation or be disproved. Thanks.

Second curly brace. Got it. I thought the else was within the nested if not outside of it.