I have a cgi script that sorts files alphabetically, so that, for example, "Best" goes before "BFF" and "102" goes before "11". For SEO purposes, I can no longer sort the analogous php array in anything other than alphabetical order. I need a php function that will sort a php array completely alphabetically. Is there seriously no automated way to do that? Do I have to go and figure out how to write a function that will sort an array alphabetically? Does anyone have such a method?
uksort(); To use without case-sensitivity, use like this: uksort($your_array, "strnatcasecmp"); Code (markup): Another is natcasesort(); Also, for future reference, take a look at this: www . php . net/manual/en/array.sorting.php Hope that helps
I'll try the uksort() example you did. I can't find thorough descriptions of "strnatcasecmp". natcasesort() does not sort alphabetically. It sorts the same style as Microsoft Windows, so that for example "11" goes before "101" even though the reverse is true when ordered alphabetically.
"strnatcasecmp" is a callback function, so: http://php.net/manual/en/function.strnatcasecmp.php Hope that helps
Neither option worked. The uksort() example had no effect on the ordering of the array. natcasesort() had the expected effect of sorting letters alphabetically but sorting numbers by actual number value, so 11 went before 101. I have to ask again, is it really this hard to sort alphabetically with something as ubiquitous as php?
<html><body> <?php $a = array("1","11","01","101","10","best", "BFF", "Bets"); echo "plain array: ";print_r($a); $a = array("1","11","01","101","10","best", "BFF", "Bets"); sort($a); echo "sort: ";print_r($a); $a = array("1","11","01","101","10","best", "BFF", "Bets"); asort($a); echo "asort: "; print_r($a); $a = array("1","11","01","101","10","best", "BFF", "Bets"); natcasesort($a); echo "natcasesort: "; print_r($a); $a = array("1","11","01","101","10","best", "BFF", "Bets"); uksort($a, "strnatcasecmp"); echo "uksort with strnatcasecmp: "; print_r($a); ?> </body></html> PHP:
So, natcasesort() is nearly there, I don't get what the problem with the numbers is, it's sorting them from lowest to highest. How do you need them sorted, as numbers aren't alphabetical...
I guess the correct term instead of "alphabetical" would be (case-insensitive) "lexicographical", sometimes called "dictionary order", but any ordered set can be appended to the alphabet to create an ordering. Dictionary ordering is the way perl searches for files in a directory, and it's the way javascript autmatically sorts arrays. The problem is that I can't go back and sort any other way because I've sorted pages by dictionary ordering forever because that's how perl created pages. I also figured something like dictionary ordering would be so useful, considering that's how analog content (books etc.) and most website content have always done it, that there would be an easy-to-implement and easy-to-find way to sort that way in PHP.