phpsortingfloating-pointcomparisonusort

usort() gives unexpected result while sorting by a column with float values


Today I provided the answer of this question and I wrote a script, but I found out that something went wrong.

Here is the first script

<?php 
$array = array( 
            "0" => array (
               "id" => 1204,
               "custom_price" => 33.1500    
            ),
            
            "1" => array (
               "id" => 1199,
               "custom_price" => 15.83  
            ),
            
            "2" => array (
               "id" => 1176,
               "custom_price" => 16.83  
            )
         );

usort($array, function($a, $b) {
    return $a['custom_price'] - $b['custom_price'];
});
echo "<pre>";
print_r($array);

and its output is (also you can check output on sandbox)

<pre>Array
(
    [0] => Array
        (
            [id] => 1176
            [custom_price] => 16.83
        )

    [1] => Array
        (
            [id] => 1199
            [custom_price] => 15.83
        )

    [2] => Array
        (
            [id] => 1204
            [custom_price] => 33.15
        )

)

So, my desired output should be sort like (custom_price 15.83, 16.83, 33.15000) but the actual output is (custom_price 16.83,15.83,33.15000). you can see 15.83 is smallest from 16.83. the sorting result is wrong

So, when I change custom_price 15.83 to 14.83 then sorting output is correct

<pre>Array
(
    [0] => Array
        (
            [id] => 1199
            [custom_price] => 14.83
        )

    [1] => Array
        (
            [id] => 1176
            [custom_price] => 16.83
        )

    [2] => Array
        (
            [id] => 1204
            [custom_price] => 33.15
        )

)

you can see output on sandbox

I can't understand what's going on.. any idea about this ?

My Question is: I check each iteration but can't identify the problem. when custom_price is 15.83 then result is wrong. why?


Solution

  • There is a warning in the PHP manual about the return values from the usort() compare function (at http://php.net/manual/en/function.usort.php#refsect1-function.usort-parameters)...

    Caution Returning non-integer values from the comparison function, such as float, will result in an internal cast to integer of the callback's return value. So values such as 0.99 and 0.1 will both be cast to an integer value of 0, which will compare such values as equal.

    Also from PHP 7. you can use the spaceship operator <=> which returns 1, 0, -1 depending on the comparison of the two values...

    usort($array, function($a, $b) {
        return $a['custom_price'] <=> $b['custom_price'];
    });
    
    echo "<pre>";
    print_r($array);