Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

usort is returning array in reverse order

Tags:

php

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"];
});
like image 428
user2720360 Avatar asked Sep 01 '13 10:09

user2720360


People also ask

How does Usort work in PHP?

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.

How do I flip an array in PHP?

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.

What is Uasort?

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.


1 Answers

usort($myArray, function($a, $b) {
    return $b["comments"] - $a["comments"];
});

Just change A to B and B to A.

like image 83
Jbadminton Avatar answered Oct 09 '22 07:10

Jbadminton