phpmultilingualalphabeticalalphabetical-sort

How to sort an array alphabetically in different languages (Spanish, French, Russian, etc.) in php?


The traditional alphabetic sorting algorithms suggested in StackOverflow for PHP serve well to sort in the English alphabetic order, but with other languages, that have a different alphabet order, or maybe even different signs, the usual sorting algorithms do not work. For example:

<?php
$palabras = ['áncora', 'avión', 'esperanza', 'élite', 'perro', 'niña', 'nina', 'ñaña'];

//Traditional sorting method
sort($palabras);
var_dump($palabras);
/*
returns an inadequate order:
array(8) {
  [0]=>
  string(6) "avión"
  [1]=>
  string(9) "esperanza"
  [2]=>
  string(4) "nina"
  [3]=>
  string(5) "niña"
  [4]=>
  string(5) "perro"
  [5]=>
  string(7) "áncora"
  [6]=>
  string(6) "élite"
  [7]=>
  string(6) "ñaña"
}
*/

How to sort these arrays in a simple manner?


Solution

  • The simplest way is to use the very useful Collator class that was developed in PHP for this explicit purposes. It has already preprogramed adequate sorting algorithms for plenty of languages and alphabets.

    This is an example of how to use it:

    <?php
    $palabras = ['áncora', 'avión', 'esperanza', 'élite', 'perro', 'niña', 'nina', 'ñaña'];   
    //Make a Collator object with the locale code of the language to sort.
    $collator = new Collator('es_ES');
    //Use Collator::sort() instead of sort() [returns a numerical array];
    //or Collator::asort() instead of asort [maintains the keys of an associative array].
    $collator->sort($palabras, Collator::SORT_REGULAR);
    var_dump($palabras);
    /*
    returns: 
    array(8) {
      [4]=>
      string(7) "áncora"
      [3]=>
      string(6) "avión"
      [0]=>
      string(6) "élite"
      [7]=>
      string(9) "esperanza"
      [2]=>
      string(4) "nina"
      [1]=>
      string(5) "niña"
      [6]=>
      string(6) "ñaña"
      [5]=>
      string(5) "perro"
    }
    */
    

    You can check the documentation here:

    The class: https://www.php.net/manual/en/class.collator.php

    The sort function: https://www.php.net/manual/en/collator.sort.php

    The asort function: https://www.php.net/manual/en/collator.asort.php