This usort function is returning the array reverse from what I want. It's returning an array like ("1", "2", "3"). How can I make it return ("3", "2", "1")?
usort($myArray, function($a, $b) {
return $a["comments"] - $b["comments"];
});
The usort() function in PHP sorts a given array by using a user-defined comparison function. This function is useful in case if we want to sort the array in a new manner. This function assigns new integral keys starting from zero to the elements present in the array and the old keys are lost.
PHP | array_reverse() Function. This inbuilt function of PHP is used to reverse the elements of an array including the nested arrays. Also, we have an option of preserving the key elements according to the users choice. This function accepts an array as parameter and returns the array with elements in reversed order.
The uasort() function sorts an array by values using a user-defined comparison function. Tip: Use the uksort() function to sort an array by keys using a user-defined comparison function.
usort($myArray, function($a, $b) {
return $b["comments"] - $a["comments"];
});
Just change A to B and B to A.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With