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?".

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

报告相同问题?