I am trying to alphabetize a variable of type array in the following way:
Code
$palabras = array(
'así',
'alfabeto',
'alfabético',
'año',
);
sort($palabras);
var_export($palabras);
Result
array (
0 => 'alfabeto',
1 => 'alfabético',
2 => 'así',
3 => 'año',
)
But as you can see, it doesn't work correctly with the accents and the "ñ", which should be sorted as if the accents weren't there, and with "n" < "ñ" < "o"
.
How can I do to sort them alphabetically without using external libraries?
If your server supports Spanish language (which it surely is) :
You will have as output, arranged the words in alphabetical order:
See this example in action here !
To perform correct alphabetical sorting, you need a multilevel sorting algorithm. Depending on your PHP installation, you may have access to the UCA (Unicode Sort Algorithm) implementation of the ICU library . If not, you will need to install the
php-intl
.You will need one
Collator
configured for Spanish ("es"
). What this algorithm does is conceptually separate the comparison into several levels, with different preferences. Thus, a difference in base letter is more important than a difference in accents, a difference in accents is more important than differences between upper and lower case, ...The object
Collator
is quite configurable, you can check it out in the PHP documentation .You just need to use the class
Collator
:You would need to do something like the following:
The list is passed by reference, which would be ordered as follows:
Note that the class is part of the Internationalization Functions
Collator
extension , which is built into PHP versions 5.3 and later. If you are using an older version of PHP, you need to install this extension manually.Anyway, if you want to make the code as portable as possible, you could always check that the class exists using the function
class_exists()
, and if not, use another more basic algorithm.This is the solution I finally used
Basing on:
Code
collator_create()
assetlocale()
they should be outside the function and run 1 time. They are there to simplify the example.Result
demo en ideone