[英]unexpected behaviour in if statement in php code
The console in a html file calling the php code shows the following results when the php code is executed: 执行php代码时,调用php代码的html文件中的控制台显示以下结果:
php processing: debug 3: TEST IF: in IF php处理:调试3:测试IF:在IF中
php processing: debug 4: false php处理:调试4:false
However, I'd expect the the first console result to be php processing: debug 3: TEST IF: in ELSE
. 但是,我希望第一个控制台结果是php processing: debug 3: TEST IF: in ELSE
Eg, it seems that according to the console the wrong (if) part of the if-else statement is executed and I don't understand why (for this very simple code)??? 例如,似乎根据控制台,如果执行了if-else语句的错误(if)部分,而我不明白为什么(对于这个非常简单的代码)?
Any suggestions? 有什么建议么?
Php code: 邮递区号:
//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 code (console.log in ajax call to php code): Javascript代码(Ajax中的console.log调用php代码):
console.log("php processing: debug 3: "+msg.debug3);
console.log("php processing: debug 4: "+msg.debug4);
The problem is you're comparing a String value to a boolean which will always evaluate to true. 问题是您正在将String值与一个布尔值进行比较,该布尔值将始终为true。 You should compare String to String like so 您应该像这样将String与String进行比较
//TEST CODE
if($productselected_form[0] == 'true')
Your $productselected_form[0]
is probably a string, not a boolean. 您的$productselected_form[0]
可能是字符串,而不是布尔值。 When using ==
, PHP converts the types so that it can compare them. 当使用==
,PHP会转换类型,以便可以比较它们。
I'm guessing you have 'false'
, not false
. 我猜你有'false'
,不是false
。 When converting to boolean, the following strings are false
: 转换为布尔值时,以下字符串为false
:
Anything else is true
. 其他任何事情都是true
。 So when you do $productselected_form[0] == true
, you are actually doing 'false' == true
, which evaluates to true
. 因此,当您执行$productselected_form[0] == true
,实际上是在执行'false' == true
,其结果为true
。
To convert 'false'
to false
you can do something like this: 要将'false'
转换为false
您可以执行以下操作:
$productselected_form[0] = ($productselected_form[0] === 'true');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.