Search code examples
phparrayssorting

Sorting a flat array returns 1 instead of the modified array


I've been trying to use the sort() function to rearrange the array from smallest to largest.

This is my print_r of the array which came from serialized data that was imploded:

Array
    (
    [0] => 127173
    [1] => 127172
    [2] => 127174
    [3] => 127175
    [4] => 127178
    [5] => 127176
    [6] => 127177
    [7] => 127179
    [8] => 127180
    [9] => 127183
    [10] => 127181
)

With sort() and asort() I just get a 1 returning.


Solution

  • Try this code... in fact the sort function is working fine.

    $array = Array
        (
        '0' => 127173,
        '1' => 127172,
        '2' => 127174,
        '3' => 127175,
        '4' => 127178,
        '5' => 127176,
        '6' => 127177,
        '7' => 127179,
        '8' => 127180,
        '9' => 127183,
        '10' => 127181
        );
    
    sort($array); // <= Sort the array desc
    
    foreach( $array as $key => $value ){
        echo $key."\t=>\t".$value."\n";
    }
    

    Consider that sort function actually alters your array and returns bool. See doc.

    Check this example online