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 trialJames Coles
2,449 PointsConditionals Confused
Question... What will be displayed in the web browser?
$username = "Treehouse"; if ($username) { if ($username != "Treehouse") { echo "Hello $username"; } } else { echo "You must be logged in"; }
I thought it would have been "You must be logged in" but it says the answer is "Hello Treehouse". Is this correct.
Surely the username is equal to tree else so it would be the else statement?
1 Answer
andren
28,558 PointsAre you sure it marked "Hello Treehouse" as correct?
When I went though the test the correct answer was "Nothing will be displayed", and that is actually (based on the code) the correct answer.
You are correct that $username
is equal to "Treehouse" so the second if statement would not run, however your conclusion that the else
statement would therefore run is incorrect. The else
statement is connected to the first if
statement, the second if
statement nested within it is entirely independent of the if/else
statements above it. Whether it runs or not has no effect on the else
statement in the layer above it.
The else
statement only cares about whether the if
statement that it is connected to ran or not, since the first if
ran the else
won't run, even when the nested if
statement does not run either. Thus in the end nothing is printed to the screen.