Sorting Closure Must Return Integers¶
Comparison closures used in custom sorting need to return an integer, while they used to yield true or false. This applies to all custom sorting functions, including usort(), uasort(), and uksort().
There is no performance penalty nor gain with the usage of that returntype.
PHP code¶
<?php
$array = [1, 2, 3];
// Replace
usort($array, fn($a, $b) : bool => $a > $b);
// With
usort($array, fn($a, $b) : int => $a <=> $b);
print_r($array);
?>
Before¶
Array
(
[0] => 1
[1] => 2
[2] => 3
)
After¶
PHP Deprecated: usort(): Returning bool from comparison function is deprecated, return an integer less than, equal to, or greater than zero
Deprecated: usort(): Returning bool from comparison function is deprecated, return an integer less than, equal to, or greater than zero
Array
(
[0] => 1
[1] => 2
[2] => 3
)
PHP version change¶
This behavior was deprecated in 8.0
This behavior changed in 9.0