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 trialjough
12,984 Pointsbasic PHP Quiz question: Why does this evaluate to true?
Why does this evaluate to true? <?php $a = "Alena"; if ($a = "Treehouse") { echo "Hello Alena, "; } echo "Welcome to Treehouse!"; ?>
The feedback given by the quiz is "Unfortunately, The value "Treehouse" is ASSIGNED to the variable $a INSTEAD of COMPARING $a to the string 'Treehouse'. Therefore the expression is evaluated as true."
I get that it's not a comparison. But it looks to me like $a is assigned to "Alena" and never reassigned. Isn't the conditional saying "IF it's true that $a = 'treehouse' (which it isnt) then perform the function, otherwise, dont, and simply echo 'welcome to treehouse'" ?
2 Answers
Ntokozo Ncube
17,435 PointsI m not fully getting your question but to compare use ==
Jennifer Nordell
Treehouse TeacherHi there, jough ! Let's take a look again at that code. This is a tricky one:
<?php
$a = "Alena";
if ($a = "Treehouse") {
echo "Hello Alena, ";
}
echo "Welcome to Treehouse!";
?>
As you correctly pointed out, the =
there is an assignment and not a comparison. It might not be immediately obvious, but when you do an assignment there is a boolean value returned. Now, this is where we get into the concept of "truthy" and "falsey". Here are some values that are considered "truthy": a non-empty string (which is the case here), a non-zero integer, a non-empty array. Here are some values that are considered "falsey": zero, an empty string, an empty array.
Because the value assigned was a non-empty string it is "truthy". This means that the assignment inside the if
evaluates to true
. But now, the value of $a
has changed from "Alena" to "Treehouse".
Hope this clarifies things!
edited for additional clarification
You stated:
IF it's true that $a = 'treehouse' (which it isnt)
No, that would be what the comparison would say. What this is saying is "IF $a
was assigned a "truthy" value"
Ntokozo Ncube
17,435 PointsNtokozo Ncube
17,435 PointsI m not fully getting your question but to compare use ==