PHP:为什么需要字符串比较函数?
比较运算符< <=> >=
也可以应用于字符串。那么为什么我们需要特殊的字符串比较函数:strcmp
?
The comparision operators < <= > >=
can be applied for strings as well. So why do we need special function for string comparision: strcmp
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
因为存在多种变化:
根据功能的不同,这些问题的答案也有所不同:
strcmp
与strcasecmp
,strnatcmp
与strnatcasecmp
)strcoll
可以)strcoll
受setlocale
影响)( 比较运算符还给出
true
或false
。strcmp
给出一个整数,因此它可以同时编码是否存在同一性(返回 0),或者如果没有,则哪个更大(取决于该值是正数还是负数)。Because there are several variations:
Depending on the function, the answer to these questions vary:
strcmp
vsstrcasecmp
,strnatcmp
vsstrnatcasecmp
)strcoll
does)strcoll
is affected bysetlocale
)Additionaly, the comparison operators also give
true
orfalse
.strcmp
gives an integer so it can encode simultaneously whether there's identity (return 0) or, if it not, which is is bigger (depending on whether the value is positive or negative).尽管 PHP 中没有对 strcmp 进行重载,但 strcmp 会产生 3 个不同的值
-1 表示小于,0 表示等于,+1 表示大于所比较的字符串。与
< =<=> >=
您(有时)需要依次进行多次检查。Although there are no overloads in PHP for strcmp, strcmp results in 3 different values
-1 for less than, 0 for equals and +1 for greater than the compared string. With
< = <= > >=
you will have (sometimes) to do multiple checks one after another.