PHP - sort strings with accents
Let's have an array with some strings:
$data = [
'Abcd',
'Efgh',
'Červený trpaslík',
'Another one',
'Špenát',
'Železo',
'Zelenina'
];
I need to sort that. When using asort($data);, the strings with accents are moved to the end of the array:
Abcd Another one Efgh Zelenina Červený trpaslík Špenát Železo
To be able to sort correctly with the accents, let's use the PHP Collator-family functions:
usort($tags,
function($a,$b) {
$coll = collator_create( 'cs_CZ' );
$aSortKey = collator_get_sort_key($coll, $a);
$bSortKey = collator_get_sort_key($coll, $b);
return $aSortKey >= $bSortKey;
}
);
Now the data is sorted correctly:
Abcd Another one Červený trpaslík Efgh Špenát Zelenina Železo