0

Possible Duplicate:
The 3 different equals

Can anyone tell me why, when using the code below, I am getting redirected to elephant.com rather than seeing a 'giraffe!

<?php
$foo="giraffe";
if($foo="elephant"){
header("location:http://www.elephant.com");
exit();
}else{
 echo $foo;}
?>

Thanks for looking

J

Community
  • 1
  • 1
Jules
  • 275
  • 1
  • 4
  • 11
  • 1
    you have **=** for assign when you want to compare with **==** And bonus points for using header-location properly, with a full URI –  Nov 07 '12 at 18:48

2 Answers2

7
if($foo="elephant")

You're assigning $foo here, rather than comparing it; you should be doing:

if($foo=="elephant")

The result of an assignment operation is the value that's just been assigned; in this case, 'elephant' is evaluating to true.

andrewsi
  • 10,807
  • 132
  • 35
  • 51
  • Doh! I am a muppet. You have no idea how long I have been staring at that. Thanks for pointing out the obvious! – Jules Nov 07 '12 at 19:21
  • No problem - it's one of those things that's very easy to overlook, until a fresh set of eyes looks at it. – andrewsi Nov 07 '12 at 19:22
1

Your if() statement has a single equal sign. This doesn't do a comparison in PHP; it sets the value and returns true.

In order to do a comparison, you need to use either a double-equal or a triple-equal sign:

if($foo == "elephant") { .... }

or

if($foo === "elephant") { .... }

The difference between the two is that double-equal doesn't care about the variable's data type, whereas triple-equal does. In this case, there's not much difference between them, but it's worth learning and understanding the differences because they can bite you if you don't know them. More info here: http://php.net/manual/en/language.operators.comparison.php

Spudley
  • 166,037
  • 39
  • 233
  • 307