Usort Issue with Decimal Numbers

usort issue with decimal numbers

See usort docs. Float result will be converted to integer. For correct work use this code:

usort(
$data,
function($a, $b) {
$result = 0;
if ($a[$_GET['sortby']] > $b[$_GET['sortby']]) {
$result = 1;
} else if ($a[$_GET['sortby']] < $b[$_GET['sortby']]) {
$result = -1;
}
return $result;
}
);

Why can this usort() function not properly sort decimals?

Casting decimal 0.5 to integer changes it to 0. Change your usort function to:

usort($customers, function($a, $b) {
if($b->score - $a->score >= 0){
return 1;
}
return -1;
});

Output:

descending order:
14
13
12.5
11
10

PHP Manual says:

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.

Sort Multi-dimensional array by decimal values

$arr = array(
array('company' => 'A', 'weight' => 4.6),
array('company' => 'B', 'weight' => 1.7),
array('company' => 'C', 'weight' => 3.7),
);

usort($arr, 'order_by_weight');

function order_by_weight($a, $b) {
return $b['weight'] > $a['weight'] ? 1 : -1;
}

var_dump($arr);

PS: it's not a rocket science - this exact "trick" is used as the first example at http://php.net/usort

Sorting an array of decimal & whole numbers

By default sorting is alphabetically. You need to pass a function to the sort method

arr.sort(function(a, b){return a-b;});

ordering strings and numbers in php

the problem is the float value. If you read the documentation you will find:

The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.

And:

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.

PHP: uasort not working

function sortByOrder($a, $b) {
$result = 0;
if ($b['rating'] > $a['rating']) {
$result = 1;
} elseif ($b['rating'] < $a['rating']) {
$result = -1;
}
return $result;
}

This ended up being my solution. It has something to do with decimal numbers, I'm not exactly sure why it worked. Solution in OP is fine if you work with whole numbers, but this is required for decimal numbers.



Related Topics



Leave a reply



Submit