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

Lee Stoka
Lee Stoka
1,104 Points

Please explain the code snippet to me

When I look at this code:

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

I would assume that the nested IF statement is asking if the username DOESN'T equal Treehouse then echo "Hello $username" to the screen. This obviously isn't the result, and when I run it in the console I get "Hello Treehouse", which is what logically is going on.

I just don't understand why the line wouldn't read:

if($username == "Treehouse") { ...

Lee Stoka
Lee Stoka
1,104 Points

I ran this code in sandbox.onlinephpfunctions.com and I go what I expected when I read the code "You must be logged in". Weirdness

1 Answer

Hey Lee,

For comparison, I believe you'll want to use the !== operator. This operator returns True /False based on comparison. != just matches the value ignoring the data type.

Take a look at the following now:

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

What do you think will print out here?