Re: sorting

From: Date: Mon, 20 Oct 2003 12:36:25 +0000
Subject: Re: sorting
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-166743@lists.php.net to get a copy of this message
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]" <M.Ford@lmu.ac.uk> To: "'Wang Feng'" <u3926286@anu.edu.au>; <php-general@lists.php.net> 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: m.ford@lmu.ac.uk > Tel: +44 113 283 2600 extn 4730 Fax: +44 113 283 3211

« previous php.general (#166743) next »