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 trial

PHP PHP Arrays and Control Structures PHP Conditionals Compare

Aaron Coursolle
Aaron Coursolle
18,014 Points

The value "Treehouse" is ASSIGNED...

Not sure how this works:

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

why is the first condition true?

Aaron Coursolle
Aaron Coursolle
18,014 Points

I even get the main point that she used one, instead of two equal signs. But shouldn't it then show a syntax error instead of becoming true?

2 Answers

andren
andren
28,558 Points

When you use an assignment in an evaluation what will be evaluated is the value that the assignment returns, assignments returns what is being assigned.

In other words:

          if ($a = "Treehouse")

Is the same as typing this:

          if ("Treehouse")

Now you are probably wondering why using a non Boolean value in an if statement does not result in some kind of error, the reason is that PHP (and a lot of other languages) will automatically convert non-Boolean values to a Boolean when you use them in a place that requires a Boolean value.

Now you are probably wondering how a non-Boolean value is converted to a Boolean value, well PHP has some rules that state that certain types of values will be treated as false, if the value in question is not one of those then it will be treated as true.

Here is a list of the values that will be treated as equivalent with false:

  • The integer 0 (zero)
  • The float 0.0 (zero)
  • The empty string, and the string "0"
  • An array with zero elements
  • An object with zero member variables (PHP 4 only)
  • The special type NULL (including unset variables)
  • SimpleXML objects created from empty tags

If the thing being converted to a Boolean matched any of those things it will get treated as false, otherwise it will get treated as true.

Since "Treehouse" is not an empty string, nor the string "0", it gets converted to the boolean value true, and hence the if statement is run.

Anthony Rouinvy
Anthony Rouinvy
10,495 Points

Short answer, you forgot the double equal sign for comparison

if ($a = "Treehouse") {

Should be

if ($a == "Treehouse") {

Code corrected

<?php
$a = "Alena";
//$a = "Treehouse";

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