phparrayssortingnumericnatural-sort

Sort a flat array of numeric strings naturally


I have a bunch of numbers. Let's use these as an example: 7, 18, 24, 53, 75, 15

When I use rsort() on my array, it orders it something like this:

However, this is not what I want. I want my sorting algorithm to sort my array in numeric order descending, so that it looks like this:

What sorting algorithm is the right one? I've tried a few but none have done the trick.


Solution

  • Use SORT_NUMERIC flag:

    rsort($myArray, SORT_NUMERIC)
    

    Without flags, rsort (as well as sort) sorts items without changing types, i.e. strings are compared lexicographically.