为什么 PHP 认为 0 等于一个字符串? [英] Why does PHP consider 0 to be equal to a string?

查看:35
本文介绍了为什么 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 评估为真,有时评估为假.*

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.

这篇关于为什么 PHP 认为 0 等于一个字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆