【问题标题】:If statement hitting when it shouldn't如果语句不应该命中
【发布时间】:2013-05-27 19:09:23
【问题描述】:

我正在运行 PHP 5.3,但遇到了一个奇怪的问题。有没有人遇到过这个问题?

if(isset($_POST['favorites'])) { $fave = $_POST['favorites']; }
elseif(isset($_GET['favorites'])) { $fave = $_GET['favorites']; } else { $fave = 0; }

echo $fave; //echoes 0

if($fave=="addto"){ //This is called and looks like $fave is temporarily set to "addto"

echo $fave; //echoes 0

}

$fave 从未设置为“addto”,但 if 语句出于某种原因将其视为“addto”。任何人以前都遇到过这种情况,或者对如何使其按应有的方式工作有任何想法?

【问题讨论】:

  • 数据类型比较(松散类型)与 == If you compare a number with a string or the comparison involves numerical strings, then each string is converted to a number and the comparison performed numerically. - php.net/manual/en/language.operators.comparison.php

标签: php variables if-statement variable-assignment


【解决方案1】:

试试这个,看看打印出什么值:

echo 'Post [Favorites]: ' . $_POST['favorites'] . '<br><br>';

if(isset($_POST['favorites'])) { 
    $fave = $_POST['favorites']; 
}elseif(isset($_GET['favorites'])) { 
    $fave = $_GET['favorites']; 
}else{ 
    $fave = 0; 
}

echo 'Value of \$fave: ' . $fave . '<br><br>';

if($fave=="addto"){ 
    //This is called and looks like $fave is temporarily set to "addto"
    echo 'Inside IF ADDTO. Value of \$fave: ' . $fave . '<br><br>';
}

【讨论】:

  • 就像 Sable 上面所说的那样,您需要使用 === 来确保它也是相同的数据类型。
  • 发布 [收藏夹]:

    \$fave 的值:0

    在 IF ADDTO 内。 \$fave 的值:0

【解决方案2】:

使用 === 比较变量类型

if($fave==="addto")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-23
    • 2022-06-11
    • 2015-10-25
    • 2017-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多