7

Problem: Need to sort an array that contains strings, for example the original name of the languages, based on specific language e.g. Greek (el), in such way that the names written in Greek will be sorted first and then the rest of the names in other languages.

Input:

$arLanguages = [
    'English',
    'Αγγλικά',
    'Русский',
    'Ρωσική',
    'Ελληνικά',
];

Expected Output:

Array
(
    [0] => Αγγλικά
    [1] => Ελληνικά
    [2] => Ρωσική
    [3] => English
    [4] => Русский
)

What I tried:

setlocale(LC_COLLATE, 'el');
asort($arLanguages);
print_r($arLanguages);

Result: Nothing happens.

EDIT: My PHP version is 7.3.

EDIT 1: A solution by Simone doesn't work for Chinese and Japanese languages. I think is something to do with multi-byte characters or because Chinese and Japanese use latin alphabet too.

Dear SO community, how the described problem could be solved in the best possible way?

Thanks for your time!

Salim Ibrohimi
  • 1,351
  • 3
  • 17
  • 35

1 Answers1

1

You can use Collator::sort

$arLanguages = [
    'English',
    'Αγγλικά',
    'Русский',
    'Ρωσική',
    'Ελληνικά',
];

$coll = collator_create( 'el' );
collator_asort( $coll, $arLanguages ); // to preserve indexes

print_r($arLanguages); //output Array ( [0] => Αγγλικά [1] => Ελληνικά [2] => Ρωσική [3] => English [4] => Русский )
Salim Ibrohimi
  • 1,351
  • 3
  • 17
  • 35
Simone Rossaini
  • 8,115
  • 1
  • 13
  • 34