PHP PHP Arrays and Control Structures PHP Conditionals Compare

Katie Taira
Katie Taira
1,774 Points

I don't understand this conditional

What will be displayed?

<?php $a = "Alena"; if ($a = "Treehouse") { echo "Hello Alena, "; } echo "Welcome to Treehouse!"; ?>

I answered "Welcome to treehouse!" but according to the quiz it is wrong and "Hello Alena, welcome to Treehouse!" is correct. In my understanding since $a is Alena and not Treehouse the if statement is false ergo only Welcome to tree house is displayed. Unless I'm not understanding something about conditionals here... Thank you.

1 Answer

Jennifer Nordell
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Staff

Hi there, Katie Taira ! I would bet that you understand conditionals just fine :smiley: If it's any consolation, this one fooled me the first time I looked at it, too.

The key lies in this line:

if ($a = "Treehouse")

That is not a comparison. That is an assignment. Remember that a single equals sign assigns a value. A double equals sign == asks if it is equal. When we have an assignment like this, if whatever is on the right side of the equals sign is "truthy" then the entire evaluation is considered true. A non-empty string is "truthy".

Now, if the question had been:

if ($a == "Treehouse")

... then your answer would likely be spot on!

Hope this helps! :sparkles:

Katie Taira
Katie Taira
1,774 Points

After I posted this question I figured out the answer but thank you for answering promptly! <3