Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP sorting arrays numerically by key value descending

Tags:

arrays

php

Is there an option in PHP to sort an array by key value descending?

I am aware that you can sort key values with ksort

like image 231
williamcarswell Avatar asked Oct 12 '11 10:10

williamcarswell


People also ask

How do you sort an array in descending order according to the value in PHP?

The arsort() function sorts an associative array in descending order, according to the value. Tip: Use the asort() function to sort an associative array in ascending order, according to the value. Tip: Use the krsort() function to sort an associative array in descending order, according to the key.

How do you sort an array of numbers in descending order?

We can use . sort((a,b)=>a-b) to sort an array of numbers in ascending numerical order or . sort((a,b)=>b-a) for descending order.

How do I sort a key in PHP?

Answer: Use the PHP ksort() and krsort() function The PHP ksort() and krsort() functions can be used for sorting an array by key.

Can array elements be sorted in descending order?

Loop through the array and select an element. Inner loop will be used to compare selected element from outer loop with rest of the elements of array. If any element is greater than the selected element then swap the values. Continue this process till entire list is sorted in descending order.


3 Answers

Yes, the krsort

$fruits = array("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple");
krsort($fruits);
like image 111
xdazz Avatar answered Oct 21 '22 04:10

xdazz


I believe krsort() is what you're looking for.

like image 36
Franz Avatar answered Oct 21 '22 05:10

Franz


http://www.php.net/manual/en/function.krsort.php krsort?

like image 33
Alex Avatar answered Oct 21 '22 04:10

Alex