2017  Kodetalk | Feedback | Privacy Policy | Terms | About
userimage

How to sort an array of strings to their natural case-insensitive order by maintains their original index association?

How to sort an array of strings to their natural case-insensitive order by maintains their original index association?

For example, the following array:

array(
    "0" => "a1",
    "1" => "a10",
    "2" => "a12",
    "3" => "a2",
    "4" => "a3",
)


After sorting, the result should be as below:

array(
    "0" => "a1",
    "3" => "a2",
    "4" => "a3",
    "1" => "a10",
    "2" => "a12",
)
userimage
The best way to solving this problem is to use three special flags with the standard asort() library function:

asort($arr, SORT_STRING|SORT_FLAG_CASE|SORT_NATURAL)

The function asort() is a variant of the standard function sort() that preserves the index association. The three flags used above SORT_STRING, SORT_FLAG_CASE and SORT_NATURAL forces the sort function to treat the items as strings, sort in a case-insensitive way and maintain natural order respectively.

Note: Using the natcasesort() function would not be a correct answer, since it would not maintain the original index association of the elements of the array.
Answer is