Reputation: 551
I am trying to get PHP to compare two values and sort them using usort()
. I have this function, which works, however this function stops running if $a == $b
,
Having this function stop running prevents further functions in the PHP file to run.
<?php
function cmp($a, $b) {
if ($a[4] == $b[4]) {
return 0;
}
return ($a[4] < $b[4]) ? -1 : 1;
}
usort($participants_times,"cmp");
?>
When there are two values that are equal, I don't mind which one is in front of the other. I have tried setting return -1
, return 0
, and return 1
when $a == $b
but they didnt work for me.
Any help is appreciated :)
Upvotes: 1
Views: 190
Reputation: 551
So the answers provided are very likely correct to my question - however, in my case, the issue was related to the form of my function()
's where I had a function inside a function and a second iteration of the initial function failed.
Moving my cmp()
function outside of the function that calls it solved my issue.
Upvotes: 0
Reputation: 3284
because you don't care the equal case, just ignore it
function cmp($a, $b) {
return ($a[4] < $b[4]) ? -1 : 1;
}
usort($participants_times,"cmp");
Upvotes: 0
Reputation: 8606
You should replace ternary operator with nested if-else statements. In your condition, it returns 1 for both >
and ==
comparison.
if ($a[4] < $b[4])
return -1;
else if ($a[4] > $b[4])
return 1;
else
return 0;
Upvotes: 1