Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does "echo strcmp('60', '100');" in php output 5?

Tags:

php

strcmp

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

like image 946
Rupert Avatar asked Feb 15 '12 07:02

Rupert


People also ask

What does strcmp return in PHP?

Return Values ¶ Returns < 0 if string1 is less than string2 ; > 0 if string1 is greater than string2 , and 0 if they are equal.

Where does PHP echo output go?

Echo simply outputs the strings that it is given, if viewing in the browser it will output the strings to the browser, if it's through command line then it will output the strings to the command line.


2 Answers

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

like image 59
wallyk Avatar answered Oct 02 '22 15:10

wallyk


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

like image 43
Madara's Ghost Avatar answered Oct 02 '22 14:10

Madara's Ghost