12

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

Rupert
  • 1,629
  • 11
  • 23

3 Answers3

13

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

wallyk
  • 56,922
  • 16
  • 83
  • 148
  • 6
    Note that this is not guaranteed behaviour -- the only thing guaranteed is that the value will be larger than zero for these input parameters. – Simon Richter Feb 15 '12 at 09:29
  • 2
    @SimonRichter: Agreed it is not guaranteed. But it *is* traditional. Some code I wrote in 1978 which depends on this method of computing the return value *still works*! – wallyk Feb 15 '12 at 17:50
  • @wallyk, how do you know that this answer is correct when the documentation didn't say that it returns the difference of the first character? – Pacerier Jul 30 '13 at 07:30
  • 1
    @Pacerier: I have a lot of experience with a lot of different runtime libraries, from PDP-11s running Unix v6 (the original C), to VAX/VMS, MSDOS, Windows, GCOS, Sequent, IBM, and microcontrollers. They all implement the difference, which, as some CRTL source code indicates, for tradition and perfect compatibility with the original. – wallyk Jul 30 '13 at 16:18
8

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

cHao
  • 84,970
  • 20
  • 145
  • 172
Madara's Ghost
  • 172,118
  • 50
  • 264
  • 308
  • @wallyk, how do you know that this behavior is guaranteed when the documentation didn't say that it returns the difference of the first character? – Pacerier Jul 30 '13 at 07:30
5

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

deceze
  • 510,633
  • 85
  • 743
  • 889