Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

PHP PHP Arrays and Control Structures PHP Conditionals Conditionals

Can someone help me break down this code? Why is the answer, nothing will happen?

~PHP Conditionals Quiz~

$username = "Treehouse"; if ($username) { if ($username != "Treehouse") { echo "Hello $username"; } } else { echo "You must be logged in"; }

2 Answers

Ryan Tiedemann
Ryan Tiedemann
3,017 Points

It may help you to have a look at the code when it is correctly formatted with spaces. See below:

$username = "Treehouse"; 
if ($username) { 
    if ($username != "Treehouse") { 
        echo "Hello $username"; 
    } 
} else { 
    echo "You must be logged in"; 
}

We can see that in the code above, the first thing that happens is that the variable $username is assigned a value of "Treehouse"

Therefore, on the second line we can infer that '''if($username)''' will return true. Thus running the code inside of the if block, and not the code inside of the else block.

After that we can see that '''if($username != "Treehouse")''' will never never return true. Because $username is always equal to Treehouse.

Therefore neither of the echo statements can ever be reached when $username is equal to "Treehouse"

I hope this helps you a little bit :)

Ryan, Your explanation made sense and helped me understand the whys. Thank you!

Antonio De Rose
Antonio De Rose
20,882 Points
$username = "Treehouse";//setting up the variable
if ($username) {//checks in, true over here
    if ($username != "Treehouse") {//comes here, to check, will not go in, as it is false here
        echo "Hello $username";
    }
} else {// it will not come here, as it had met the outer if condition for true
    echo "You must be logged in";
}

Antonio -thank you for explaining the code.