php代码中的if语句中的意外行为

时间:2013-08-23 16:00:56

标签: php javascript

调用php代码的html文件中的控制台在执行php代码时显示以下结果:

  

php处理:调试3:TEST IF:在IF

中      

php处理:debug 4:false

但是,我希望第一个控制台结果为php processing: debug 3: TEST IF: in ELSE。例如,似乎根据控制台if-else语句的错误(if)部分被执行而我不明白为什么(对于这个非常简单的代码)???

有什么建议吗?

Php代码:

//TEST CODE
if($productselected_form[0] == true)
{
    $response_array['debug3'] = 'TEST IF: in IF';
}
else
{
    $response_array['debug3'] = 'TEST IF: in ELSE';
}
$response_array['debug4'] = $productselected_form[0];

//send the response back
echo json_encode($response_array);
//END TEST CODE

Javascript代码(ajax调用php代码中的console.log):

console.log("php processing: debug 3: "+msg.debug3);
console.log("php processing: debug 4: "+msg.debug4);

2 个答案:

答案 0 :(得分:4)

问题是你将String值与一个总是评估为true的布尔值进行比较。您应该像这样将String与String进行比较

//TEST CODE
if($productselected_form[0] == 'true')

答案 1 :(得分:2)

你的$productselected_form[0]可能是一个字符串,而不是一个布尔值。使用==时,PHP会转换类型以便比较它们。

我猜测你有'false',而不是false。转换为布尔值时,以下字符串为false

  • ' 0'
  • '' (空字符串)

其他任何内容都是true。因此,当您执行$productselected_form[0] == true时,您实际上正在执行'false' == true,其评估结果为true


要将'false'转换为false,您可以执行以下操作:

$productselected_form[0] = ($productselected_form[0] === 'true');