为什么PHP认为0等于字符串? [英] Why does PHP consider 0 to be equal to a string?
问题描述
我有以下代码:
$item['price'] = 0;
/* Code to get item information goes in here */
if($item['price'] == 'e') {
$item['price'] = -1;
}
它旨在将物料价格初始化为0,然后获取有关其的信息.如果价格被告知为"e",则表示交换而不是卖出,后者以负数存储在数据库中.
It is intended to initialize the item price to 0 and then get information about it. If the price is informed as 'e' it means an exchange instead of a sell, which is stored in a database as a negative number.
也有可能将价格保留为0,这是因为该项目是奖励商品,或者是因为价格将在以后设置.
There is also the possibility to leave the price as 0, either because the item is a bonus or because the price will be set in a later moment.
但是,每当未设置价格时,将其保留为初始值0,则上述if
循环的计算结果为true,并且价格设置为-1.也就是说,它认为0等于"e".
But, whenever the price is not set, which leaves it with the initial value of 0, the if
loop indicated above evaluates as true and the price is set to -1. That is, it considers 0 as equal to 'e'.
这怎么解释?
当价格为0(初始化后)时,该行为是不稳定的:有时if的评估结果为true,有时它的评估结果为false.*
When the price is provided as 0 (after initialization), the behavior is erratic: sometimes the if evaluates as true, sometimes it evaluates as false.*
推荐答案
您正在做==
,它会为您分类类型.
You are doing ==
which sorts out the types for you.
0
是一个整数,因此在这种情况下它将把'e'
强制转换为一个整数.不可解析为1,它将变为0
.字符串'0e'
将变为0
并且匹配!
0
is an int, so in this case it is going to cast 'e'
to an int. Which is not parsable as one and will become 0
. A string '0e'
would become 0
and would match!
使用===
这篇关于为什么PHP认为0等于字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!