Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Sorts Uppercase characters before lowercase characters

Tags:

php

sorting

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?

like image 231
xms Avatar asked Feb 21 '26 16:02

xms


1 Answers

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

like image 158
chris85 Avatar answered Feb 24 '26 05:02

chris85