Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array sorting case-sensitivity

Tags:

php

sorting

I'm just wondering why the ksort() function sorts uppercase keys first and then lowercase keys by default?

What is the logic beyond this?

like image 761
Boris Delormas Avatar asked Nov 23 '25 19:11

Boris Delormas


2 Answers

It seems you're familiar with the fact that ksort() is case sensitive.

The reason is unclear to me, but there's an easy solution.

uksort() allows you to sort an array with an user-defined function, however, lazy as we are, we don't want to define our own function and use a native one. The function strcasecmp() allows us to compare a string in an case-insensitive way and works the very same way when we would define our own function. When a string has a high value, a value bigger than 0 is returned. If the value is smaller, a smaller value is returned and if it's equal, the function returns 0. So, a perfect candidate for our uksort() function.

This will work for you: $sorted = uksort($array, 'strcasecmp');

like image 195
Tim S. Avatar answered Nov 26 '25 10:11

Tim S.


uppercase value smaller than lowercase values.

eg:- in ascii. A - 65, a - 97

like image 20
Dinuka Thilanga Avatar answered Nov 26 '25 10:11

Dinuka Thilanga