为什么PHP在[松散地]比较之前将两个数字字符串转换为数字? [英] Why PHP casts two numerical strings to numbers before [loosely] comparing them?

查看:141
本文介绍了为什么PHP在[松散地]比较之前将两个数字字符串转换为数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我浏览了几个类似的问题,但都只说明了事实:

I browsed through several similar questions, but they all only state the fact:


如果...比较涉及数字字符串,则每个字符串转换为数字,并以数字的方式执行比较。

好吧,我得到了。当'00001'=='1'返回 TRUE 时,它解释了 。

Okay, I got it. It explains what is going on when '00001' == '1' returns TRUE.

问题是: 为什么PHP

探测字符串是数字,然后投射如果是这样?为什么我们不能只比较两个字符串了?

The question is: Why PHP does so?
What is the reason for probing strings for being numeric, and then casting if so? Why can't we just compare two strings already?

如果两个操作数有不同的类型,我可以相当理解需要什么类型的转换。但为什么它会通常的数学时是字符串?

I can fairly understand what casting is required if two operands has different types. But why it does "usual math" when both are strings?

推荐答案

啊,这是我很蠢。

比较不仅涉及等于,还包括少于 code>和大于。对于后两种情况,在比较之前强制转换数字操作数是很关键的,因为数字通常在PHP中表示为字符串,并且11必须大于9,即使它们都存储在字符串中。

Comparison involves not only "is equal" but also "less than" and "greater than". And for the latter two it is obviously critical to cast numerical operands before comparison, because numbers often being represented in PHP as strings, and 11 have to be greater than 9 even if both stored in strings.

所以,作为 compare_function() 会立即进行所有比较,返回 1,0,-1 来告诉第一个操作数是否大于,等于或小于秒 - 好吧,它是相当解释,为什么要操作数。

So, as compare_function() does all the comparisons at once, returns either 1, 0, -1 to tell if first operand is bigger, equal or less than second respectively - well, it's fairly explains, why operands being cast.

这篇关于为什么PHP在[松散地]比较之前将两个数字字符串转换为数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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