Search code examples
phparrayssortingassociative-arraynumeric

Sort a flat array of numeric strings and preserve keys


I have a PHP array like:

myarr[1] = "1",
myarr[2] = "1.233",
myarr[3] = "0",
myarr[4] = "2.5"

The values are actually strings, but I want this array to be sorted numerically. The sorting algorithm should respect float values and maintaining index association.


Solution

  • You can use the normal sort function. It takes a second parameter to tell how you want to sort it. Choose SORT_NUMERIC.

    Example:

      sort($myarr, SORT_NUMERIC); 
      print_r($myarr);
    

    prints

    Array
    (
        [0] => 0
        [1] => 1
        [2] => 1.233
        [3] => 2.5
    )
    

    Update: For maintaining key-value pairs, use asort (takes the same arguments), example output:

    Array
    (
        [3] => 0
        [1] => 1
        [2] => 1.233
        [4] => 2.5
    )