Yesterday at work I stumbled upon a piece of code that was roughly like this:
uasort($array, function($a, $b) {
return isset($a['sort_code']) && isset($b['sort_code']) && $a['sort_code'] > $b['sort_code'];
});
this flipped a couple of switches in my head seeing as this can only return a boolean true or false instead of the 0 1 or -1 that is clearly stated in php.net. Best case scenario PHP will interpret false as 0 and true as 1. So one (the colleague that wrote this) could argue that it actually works.
I made the argument that it cannot possibly work because it will never ever ever return a -1. There is a state missing in this return-either-true-or-false from the sort callback and the way I think this is you will get either a wrong result or the process is not as performant.
I actually got down to writing a couple of tests and though I am no expert in sorting I actually got to the point where you could actually do away with the -1 state and still get a correct sorting with the same amount of calculations
effectively you could replace:
if ($a === $b) {
return 0;
}
return $a < $b ? -1 : 1;
with
return $a > $b;
Now, as I said, I am by no means an expert in sorting and my tests were less than thorough. However my results with small and bigger arrays showed that this is true. The array always got sorted correctly with the amount of calculations being the same using either method
So it really doesnt seem to be that big of a matter that there is no third state (-1)
I still stand by my opinion that you should follow the docs, especially PHP, to the letter. When php says I need either 0, a negative or positive number then that is exactly what one should do. You shouldnt leave stuff like that to chance and watch how things work by accident.
However I am intrigued by all this and would like some insight from somebody who knows more
thoughts? anyone?