为什么“echo strcmp('60', '100');”在php输出5中?

发布于 2025-01-05 21:55:50 字数 736 浏览 1 评论 0原文

PHP 关于这个函数的文档有点稀疏,我读到这个函数比较 ASCII 值,所以......

echo strcmp('hello', 'hello');
//outputs 0 as expected - strings are equal.
echo '<hr />';

echo strcmp('Hello', 'hello');
//outputs -32, a negative number is expected as 
//uppercase H has a lower ASCII value than lowercase h.
echo '<hr />';

echo strcmp('60', '100');
//outputs 5.

最后一个例子让我感到困惑。我不明白为什么它输出正数。

  • ASCII 值 0 = 48
  • ASCII 值 1 = 49
  • ASCII 值 6 = 54

  • “60”的总 ASCII 值 = (54 + 48) = 102< /p>

  • '100' 的总 ASCII 值 = (49 + 48 + 48) = 145

strcmp() 函数表示“60”“大于”“100”,尽管“100”的 ASCII 值字符串长度似乎大于'60'

谁能解释一下原因吗?

谢谢

PHP's documentation on this function is a bit sparse and I have read that this function compares ASCII values so...

echo strcmp('hello', 'hello');
//outputs 0 as expected - strings are equal.
echo '<hr />';

echo strcmp('Hello', 'hello');
//outputs -32, a negative number is expected as 
//uppercase H has a lower ASCII value than lowercase h.
echo '<hr />';

echo strcmp('60', '100');
//outputs 5.

The last example is confusing me. I don't understand why it is outputting a positive number.

  • ASCII Value of 0 = 48
  • ASCII Value of 1 = 49
  • ASCII Value of 6 = 54

  • Total ASCII value of '60' = (54 + 48) = 102

  • Total ASCII value of '100' = (49 + 48 + 48) = 145

The strcmp() functions is saying that '60' is "greater" than '100' even though it seems that the ASCII value and string length of '100' is greater than '60'

Can anyone explain why?

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

拥抱我好吗 2025-01-12 21:55:50

strcmp() 返回字符串之间第一个不匹配字符的差异。

6 - 1 是 5。

当您查看它时,您可能看不到字符或数字 - 只是数字

strcmp() returns the difference of the first non-matching character between the strings.

6 - 1 is 5.

When you look at it, you are probably not seeing the characters or digits—just the numbers

楠木可依 2025-01-12 21:55:50

因为 strcmp() 在找到的第一个差异处停止。因此,ASCII 值“1”和 ASCII 值“6”之间存在差异

Because strcmp() stops at the first difference it finds. Hence the difference between the ASCII value of '1' and the ASCII value of '6'

情丝乱 2025-01-12 21:55:50

6 比 1 “大”5。这是词法比较。第一个字符不同,这就是比较停止的地方。

6 is 5 "larger" than 1. This is lexical comparison. The first character is different, that's where the comparison stops.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文