Mike, So, in PHP, when a string is converted to a number to compare with the other decimal input, the compiler doesn't look at the ascii set table *at all*? Instead, it simply convert the string to 0?
cheers, feng ----- Original Message ----- From: "Ford, Mike [LSS]" <[EMAIL PROTECTED]> To: "'Wang Feng'" <[EMAIL PROTECTED]>; <[EMAIL PROTECTED]> Sent: Monday, October 20, 2003 10:18 PM Subject: RE: [PHP] sorting > On 18 October 2003 10:10, Wang Feng wrote: > > > I can't uderstand why the number 18 is stored in the $third > > rather than > > $first. I tried to change the 18 to "18", that is, change it > > from a decimal > > number to a string and by that way, "18" is stored in the $first, > > which is what I expected. But why doesn't 18 work? > > > > My understanding is that the compiler checks the ascii set > > when it deals > > with sorting. So, why the number 18 is *greater* than string "blue" > > and "large" in the ascii? > > This is all to do with how PHP handles comparison of different types to each other. > > When that sort is run on > > array("large", "blue", 18.00) > > the comparison of "large" to "blue" is fine, because both are strings so there's no type conversion involved. However, the comparison of 18.00, a number, to either "blue" or "large", both strings, necessarily involves a type conversion, and the rules PHP uses says that when comparing a number with a string, the string should be converted to a number and teh comparison performed using the two numbers -- and both "blue" and "large", when converted to a number, are represented by 0, which sorts before 18, so bingo! > > Now, if you make the array into > > array("large", "blue", "18.00") > > then all the comparisons are string-ti-string, so there are no type conversions involved, so your sort proceeds exactly how you expect. > > If you wish to sort an array containing values of more than one type, then you must either be fully aware of these type-conversion rules and accept the slightly odd results they will sometimes give you, or use one of the optional sort flags -- SORT_STRING or SORT_NUMERIC -- to force a more uniform comparison. But don't forget that if you use SORT_STRING and have an array containing numbers, you will get a textual sort of those numbers -- for example: 1, 5, 33, 297 would sort as "1", "297", "33", "5"!! > > Cheers! > > Mike > > --------------------------------------------------------------------- > Mike Ford, Electronic Information Services Adviser, > Learning Support Services, Learning & Information Services, > JG125, James Graham Building, Leeds Metropolitan University, > Beckett Park, LEEDS, LS6 3QS, United Kingdom > Email: [EMAIL PROTECTED] > Tel: +44 113 283 2600 extn 4730 Fax: +44 113 283 3211 -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php