I'm using PHP and having problems with different sorting functions, such as sort and usort. Here is an example.
$taulu[] = "Ahola";
$taulu[] = "AL-mara";
$taulu[] = "Aalto";
$taulu[] = "A. Pek";
sort($taulu);
foreach ($taulu as $rivi)
{
echo "$rivi<br />";
}
This will print:
A. Pek
AL-mara
Aalto
Ahola
I want it to be this way:
A. Pek
Aalto
Ahola
AL-mara
How could that be possible?
Update
$taulu[] = "Ahola";
$taulu[] = "AL-mara";
$taulu[] = "Aalto";
$taulu[] = "A. Pek";
$taulu[] = "AaltoNen";
$taulu[] = "Aalto nen";
sort($taulu, SORT_NATURAL | SORT_FLAG_CASE);
print_r($taulu);
On https://3v4l.org/sZdfa the output on the section "Output for hhvm-3.10.1 - 3.19.0, 7.0.0 - 7.2.0alpha2" is incorrect, but on the section "Output for 5.4.0 - 5.6.30" the output is 100% correct. When using PHP 5.6.23 on https://eval.in, the code works fine. Anyway, on my server with PHP 5.6.30 this does not work.
So, why does this not work in all cases?
The reason your array is sorted that way is because PHP will sort Uppercase characters before lowercase ones.
One solution to this would be to just compare the strings in a case-insensitive manner, using strcasecmp as a comparison function.
You can try this:
usort($array, strcasecmp); // Sort array using `strcasecmp` as the comparison function
Use SORT_NATURAL | SORT_FLAG_CASE
, then it will sort by the characters (regardless of the case)
$taulu[] = "Ahola";
$taulu[] = "AL-mara";
$taulu[] = "Aalto";
$taulu[] = "A. Pek";
sort($taulu, SORT_NATURAL | SORT_FLAG_CASE);
print_r($taulu);
Demo: https://eval.in/823308
In your case you can use natcasesort
just like this:
<?php
$taulu[] = "Ahola";
$taulu[] = "AL-mara";
$taulu[] = "Aalto";
$taulu[] = "A. Pek";
natcasesort($taulu);
foreach ($taulu as $rivi)
{
echo "$rivi<br />";
}
?>
This will be working fine.