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 if statement - can someone clarify?

I am struggling to get my head around something:

"What will be displayed in a browser when the following PHP code is executed:

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

TIP: Check the OPERATORS"

The variable $a is - Alena.

but surely there is an issue with if ($a = "Treehouse") {

is $a not Alena any more?

3 Answers

Antonio Benincasa
Antonio Benincasa
5,956 Points

In the if statement to check if a value is equal to another value you have to use '==' instead of '=' ( '=' is for assignments) or '===' if you also need to check if the values are of the same type.

For Example:

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

Hi Antonio thanks for your reply

So,

$a = Alena (or $a is Alena) if $a is equal to Treehouse then echo Hello Alena Other wise, echo Welcome to Treehouse!

Is my thinking right?

Thanks

Steve

Antonio Benincasa
Antonio Benincasa
5,956 Points

No, in this case, PHP will print anyway "Welcome to treehouse". Because there is no else\else if statement.

But if you want to do that, this is the way:

<?php
 $a = "Alena";   // Try to change the value of the variable to understand the beaviour
if ($a == "Alena") {
  echo "Hello Alena, "; 
} else{
  echo "Welcome to Treehouse!"; 
}
?>

Or

<?php
 $a = "Alena";   // Try to change the value of the variable to understand the beaviour
if ($a == "Alena") {
  echo "Hello Alena, "; 
} else if ($a == "Treehouse"){
  echo "Welcome to Treehouse!"; 
}
?>
Robert Leonardi
Robert Leonardi
17,151 Points

The "echo "Welcome to Treehouse!"; " is just a trick so that you'll get confused if it is together package with the if or not.

The "$a = "Treehouse"" inside if is replacing $a from "Alena" to "Treehouse", so obviously becomes TRUE thus, "Hello Alena" appears.

The $a becomes "Treehouse"