dongyan9950 2017-05-30 18:28
浏览 60
已采纳

请给我一个PHP字符串函数strcmp()的深入分析

Consider the following program:

<?php
      $str1='Hello';
      $str2='hELLo';
      echo strcmp($str1,$str2);
?>

As per my knowledge:

  1. At the point where first mismatch is found the ASCII value difference of the two characters are given.

  2. If the first mismatch is found between a valid character and an empty character the extra number of characters of longer string is given as output.

Hence, the output of above character should be

ASCII value of H - ASCII value of h = 72 - 104 = - 32

My browser gives the same output as well.

However in w3school

the answer is given as -1

Also in phpdotnet

in user contributed notes section, user luizvid at gmail dot come puts forward similar concept as given in w3schools.

Please clear my confusion.

  • 写回答

1条回答 默认 最新

  • dqdl6469 2017-05-30 19:01
    关注

    To wrap this question up:

    The PHP docs generally just state that you can rely on the sign of the result:

    Returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.

    The effect that it returns the ASCII difference is just that, a side-effect and not guaranteed.

    In fact, as of 2017-05-30:

    • PHP 5.6.0 - 5.6.30 aswell as 7.0.0 - 7.1.5 return the ASCII difference

    while

    • HHVM 3.15.4 - 3.19.0 just returns the sign.

    See Link.

    Long story short: Don't rely on strcmp for anything other than "Are these strings identical or not?".

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器