Retourner un int, pas un bool
<?php
$array = range(0, 10);
usort($array, withBool(...));
print(implode(', ', $array)).PHP_EOL;
// 9, 10, 7, 8, 5, 6, 4, 3, 2, 1, 0
usort($array, withInt(...));
print(implode(', ', $array)).PHP_EOL;
// 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
function withBool($a, $b) : bool { return $a <=> $b; }
function withInt($a, $b) : int { return $a <=> $b; }
?>
Il existe un avertissement de dépréciation particulier lors de l’utilisation d’une clôture pour trier un tableau : Deprecated: usort(): Returning bool from comparison function is deprecated, return an integer less than, equal to, or greater than zero.
Et si cette dépréciation est ignorée, le booléen est automatiquement converti en entier. Comme PHP transforme 0 en false, et tout le reste, y compris 1 et -1, en true, cela conduit à des effets de tri surprenants.
Faites simplement confiance à l’avis de dépréciation.
See Also
PHP Error Messages
PHP Features
Last updated: 22 October 2026