PHP executing header:location regardless IF statement parameters

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


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.


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

链接地址: http://www.djcxy.com/p/58472.html

上一篇: 导航栏当前类更改php包括

下一篇: PHP执行头文件:位置,无论IF语句参数