Problem with If statement execution

I’m new to php. When I run this code …

[php]

<?php $requestInfo2 = "Listen"; print $requestInfo2."
"; if ($requestInfo2 = "Offers") { echo "Variable = Offers!"; } elseif ($requestInfo2 = "Listen") { echo "Variable = Listen!"; } ?>

[/php]

I get output of

Listen
Variable = Offers!

Trying to figure out why it fails.

Thanks

Instead of this
[php] <?php
$requestInfo2 = “Listen”;
print $requestInfo2."
";
if ($requestInfo2 = “Offers”) {
echo “Variable = Offers!”;
} elseif ($requestInfo2 = “Listen”) {
echo “Variable = Listen!”;
}
?>[/php]
it should be
[php] <?php
$requestInfo2 = “Listen”;
print $requestInfo2."
";
if ($requestInfo2 === “Offers”) {
echo “Variable = Offers!”;
} elseif ($requestInfo2 === “Listen”) {
echo “Variable = Listen!”;
}
?>[/php]

I like using === instead of ==, for if you accidentally leave an equal sign out you should be OK. Three equal signs is an exact match and 99 percent of the time it works OK; however, if by chance it doesn’t then try 2 equal signs to see if it fixes the problem. It’s a trick that someone showed me when I ran into that problem. BTW if you have more elseif statements I would check into using a switch statement.

What is failing? It is doing exactly what you’re telling it to do. What results are you expecting?

since $requestInfo2 = “Listen” - I’m expecting the output to be

Variable = Offers!

As Strider pointed out, that isn’t what is actually happening.

[php]
$requestInfo2 = “Listen”;
print $requestInfo2."
";
if ($requestInfo2 = “Offers”) {
// $requestInfo2 no equals “Offers”
echo “Variable = Offers!”;
} elseif ($requestInfo2 = “Listen”) {
// $requestInfo2 no equals “Listen”
echo “Variable = Listen!”;
}
[/php]

Comparison is ==
Assignment is =

You are assigning the new value, not checking if that is the value.

i got it!

Sponsor our Newsletter | Privacy Policy | Terms of Service