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

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,885 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.