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 trialLee Stoka
1,104 PointsPlease 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") { ...
1 Answer
jacobproffer
24,604 PointsHey 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?
Lee Stoka
1,104 PointsLee Stoka
1,104 PointsI ran this code in sandbox.onlinephpfunctions.com and I go what I expected when I read the code "You must be logged in". Weirdness