PHP PHP Arrays and Control Structures PHP Conditionals Compare

Peninah Adler
Peninah Adler
3,843 Points

Quiz result said that a variable was assigned, not compared -- trying to understand.

I'm doing a quiz in beginner php. Here's the question --

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

I thought the string in the if statement would not be output, but I was incorrect. However, I don't understand the answer:

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 don't understand why it's assigned and not comparing...

3 Answers

KRIS NIKOLAISEN
KRIS NIKOLAISEN
54,287 Points

It shouldn't be assigned but that is the code provided and what you have to work with. It's kind of trick question and the reason for the tip.

For

if ($a = "Treehouse")

($a = "Treehouse") evaluates to true because "Treehouse" is a truthy value.

See this page where you will find:

The value of an assignment expression is the value assigned. That is, the value of "$a = 3" is 3.

jamesjones21
jamesjones21
9,246 Points

You are missing an extra equal symbol to compare that $a is equal to 'Aleana'.

So the single equal symbol is the assignment operator where you are assigning 'Aleana' to $a. So the comparison operator == can be used to compare the variable against the string within the conditional. You also have the identical operator === which means that the variable that you are comparing must be of the same type and the same value.

Hope this helps :)

Peninah Adler
Peninah Adler
3,843 Points

Thanks! These both helped me understand.