Need help with PHP 8.1 and usort() function

amiga4ever

New member
I have extensions in Magento 2 with deprecated function

"main.CRITICAL: Exception: Deprecated Functionality: uasort(): Returning bool from comparison function is deprecated, return an integer less than, equal to, or greater than zero"
how to modify this function to make it works in PHP 8.1?

protected function sortItemsByPrice($items, $order)
{
usort($items, [$this, $order . "Sort"]); //this line throw this error
return $items;
}
 
Well, in my opinion, you can add a comparison function, and I hope you can get what you are looking for. Lets try below code and confirm have you solved your problem with below code or not ?

protected function sortItemsByPrice($items, $order)
{
usort($items, function ($a, $b) use ($order) {
// Implement your custom comparison logic here
if ($a->getPrice() == $b->getPrice()) {
return 0;
}
return ($a->getPrice() < $b->getPrice()) ? -1 : 1;
});

return $items;
}

Thanks
 
Simplify the comparison logic by using the spaceship operator ('<=>')

protected function sortItemsByPrice($items, $order)
{
usort($items, function ($a, $b) use ($order) {
return $a->getPrice() <=> $b->getPrice();
});
return $items;
}
 
Back
Top