Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sort array in DESC order

How can i sort this array by arrray key

array(
4 => 'four',
3 => 'three',
2 => 'two',
1 => 'one',
)

like this

array(
1 => 'one',
2 => 'two',
3 => 'three',
4 => 'four',
)
like image 457
antpaw Avatar asked Jan 11 '10 22:01

antpaw


People also ask

How do you sort in descending order?

The ORDER BY keyword is used to sort the result-set in ascending or descending order. The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword.

How do you sort an array in ascending order C++?

Here, first – is the index (pointer) of the first element in the range to be sorted. last – is the index (pointer) of the last element in the range to be sorted. For example, we want to sort elements of an array 'arr' from 1 to 10 position, we will use sort(arr, arr+10) and it will sort 10 elements in Ascending order.

How do you sort an array in ascending and descending order in Java?

We can sort arrays in ascending order using the sort() method which can be accessed from the Arrays class. The sort() method takes in the array to be sorted as a parameter. To sort an array in descending order, we used the reverseOrder() method provided by the Collections class.


2 Answers

If you want to sort the keys in DESC order use:

krsort($arr);

If you want to sort the values in DESC order and maintain index association use:

arsort($arr);

If you want to sort the values in DESC natural order and maintain index association use:

natcasesort($arr);
$arr = array_reverse($arr, true);
like image 78
Alix Axel Avatar answered Oct 18 '22 10:10

Alix Axel


If you just want to reverse the order, use array_reverse:

$reverse = array_reverse($array, true);

The second parameter is for preserving the keys.

like image 38
Gumbo Avatar answered Oct 18 '22 08:10

Gumbo