为什么 PHP 认为 0 等于字符串?
我有以下代码:
$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
循环评估为真,价格设置为 -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
是一个 int,所以在这种情况下,它会将 'e'
转换为一个 int.不能作为一个解析,将成为 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.net:
使用 == 和其他非严格的字符串和数字之间的比较比较运算符目前通过将字符串转换为数字来工作,并随后对整数或浮点数进行比较.这导致许多令人惊讶的比较结果,最值得注意的是那就是 0 == foobar";返回真.
Comparisons between strings and numbers using == and other non-strict comparison operators currently work by casting the string to a number, and subsequently performing a comparison on integers or floats. This results in many surprising comparison results, the most notable of which is that 0 == "foobar" returns true.
然而,这种行为在 PHP 8.0:
当与数字字符串进行比较时,PHP 8 使用数字比较.否则,它将数字转换为字符串并使用字符串比较.
When comparing to a numeric string, PHP 8 uses a number comparison. Otherwise, it converts the number to a string and uses a string comparison.
PHP 7
0 == 'foobar' // true
0 == '' // true
4 == '4e' // true (4e is cast as a number and becomes 4)
PHP 8 在进行比较之前将数字转换为字符串
PHP 8 converts numbers to strings before making comparisons
0 == 'foobar' // false
0 == '' // false
4 == '4e' // false ('4e' is considered non-numeric therefore 4 is cast as a string and becomes '4')
这是一个重大变化,因此它是在一个新的主要 PHP 版本中实现的.此更改破坏了依赖于旧行为的脚本的向后兼容性.
This is a major change therefore it was implemented in a new major PHP version. This change breaks backward compatibility in scripts that depend on the old behavior.
相关文章