Php sort array by key descending


The elements in an array can be sorted in alphabetical or numerical order, descending or ascending.


PHP - Sort Functions For Arrays

In this chapter, we will go through the following PHP array sort functions:

  • sort() - sort arrays in ascending order
  • rsort() - sort arrays in descending order
  • asort() - sort associative arrays in ascending order, according to the value
  • ksort() - sort associative arrays in ascending order, according to the key
  • arsort() - sort associative arrays in descending order, according to the value
  • krsort() - sort associative arrays in descending order, according to the key

Sort Array in Ascending Order - sort()

The following example sorts the elements of the $cars array in ascending alphabetical order:

Example

<?php
$cars = array("Volvo", "BMW", "Toyota");
sort($cars);
?>

Try it Yourself »

The following example sorts the elements of the $numbers array in ascending numerical order:



Sort Array in Descending Order - rsort()

The following example sorts the elements of the $cars array in descending alphabetical order:

Example

<?php
$cars = array("Volvo", "BMW", "Toyota");
rsort($cars);
?>

Try it Yourself »

The following example sorts the elements of the $numbers array in descending numerical order:


Sort Array (Ascending Order), According to Value - asort()

The following example sorts an associative array in ascending order, according to the value:

Example

<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
asort($age);
?>

Try it Yourself »


Sort Array (Ascending Order), According to Key - ksort()

The following example sorts an associative array in ascending order, according to the key:

Example

<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
ksort($age);
?>

Try it Yourself »


Sort Array (Descending Order), According to Value - arsort()

The following example sorts an associative array in descending order, according to the value:

Example

<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
arsort($age);
?>

Try it Yourself »


Sort Array (Descending Order), According to Key - krsort()

The following example sorts an associative array in descending order, according to the key:

Example

<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
krsort($age);
?>

Try it Yourself »


Complete PHP Array Reference

For a complete reference of all array functions, go to our complete PHP Array Reference.

The reference contains a brief description, and examples of use, for each function!


PHP Exercises



You have an array, you want to sort it by keys, in reverse order -- you can use the krsort function :

Sorts an array by key in reverse order, maintaining key to data correlations. This is useful mainly for associative arrays.


In you case, you'd have this kind of code :

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

krsort($arr);
var_dump($arr);

which would get you this kind of output :

$ /usr/local/php-5.3/bin/php temp.php
array(4) {
  [4]=>
  string(4) "four"
  [3]=>
  string(5) "three"
  [2]=>
  string(3) "two"
  [1]=>
  string(3) "one"
}


As a sidenode : if you had wanted to sort by values, you could have used arsort -- but it doesn't seem to be what you want, here.

(PHP 4, PHP 5, PHP 7, PHP 8)

krsortSort an array by key in descending order

Description

krsort(array &$array, int $flags = SORT_REGULAR): bool

Note:

If two members compare as equal, they retain their original order. Prior to PHP 8.0.0, their relative order in the sorted array was undefined.

Note:

Resets array's internal pointer to the first element.

Parameters

array

The input array.

flags

The optional second parameter flags may be used to modify the sorting behavior using these values:

Sorting type flags:

  • SORT_REGULAR - compare items normally; the details are described in the comparison operators section
  • SORT_NUMERIC - compare items numerically
  • SORT_STRING - compare items as strings
  • SORT_LOCALE_STRING - compare items as strings, based on the current locale. It uses the locale, which can be changed using setlocale()
  • SORT_NATURAL - compare items as strings using "natural ordering" like natsort()
  • SORT_FLAG_CASE - can be combined (bitwise OR) with SORT_STRING or SORT_NATURAL to sort strings case-insensitively

Return Values

Always returns true.

Examples

Example #1 krsort() example

<?php
$fruits 
= array("d"=>"lemon""a"=>"orange""b"=>"banana""c"=>"apple");
krsort($fruits);
foreach (
$fruits as $key => $val) {
    echo 
"$key = $val\n";
}
?>

The above example will output:

d = lemon
c = apple
b = banana
a = orange

See Also

  • sort() - Sort an array in ascending order
  • ksort() - Sort an array by key in ascending order
  • The comparison of array sorting functions

Anonymous

17 years ago

To create a natural reverse sorting by keys, use the following function:

<?php
function natkrsort($array)
{
   
$keys = array_keys($array);
   
natsort($keys);

    foreach (

$keys as $k)
    {
       
$new_array[$k] = $array[$k];
    }
$new_array = array_reverse($new_array, true);

    return

$new_array;
}
?>

peter at pmkmedia dot com

18 years ago

Best deal sorting:

This is a function that will sort an array with integer keys (weight) and float values (cost) and delete 'bad deals' - entries that are more costly than other entries that have greater or equal weight.

Input: an array of unsorted weight/cost pairs
Output: none

function BEST_DEALS($myarray)
{   // most weight for least cost:
    // ? Peter Kionga-Kamau, http://www.pmkmedia.com
    // thanks to Nafeh for the reversal trick
    // free for unrestricted use.
    krsort($myarray, SORT_NUMERIC);
    while(list($weight, $cost) = each($myarray))
    {   // delete bad deals, retain best deals:
        if(!$lastweight)
        {
            $lastweight=$weight;
            $lastcost = $cost;
        }
        else if($cost >= $lastcost) unset($myarray[$weight]);
        else
        {
            $lastweight=$weight;
            $lastcost = $cost;
        }
    }
    ksort($myarray);
}

How do I arrange an array in descending order in PHP?

rsort() - sort arrays in descending order. asort() - sort associative arrays in ascending order, according to the value. ksort() - sort associative arrays in ascending order, according to the key. arsort() - sort associative arrays in descending order, according to the value.

How do you sort an array in descending order?

To sort an array in Java in descending order, you have to use the reverseOrder() method from the Collections class. The reverseOrder() method does not parse the array. Instead, it will merely reverse the natural ordering of the array.

How do I sort an array by key?

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

What is Rsort PHP?

The rsort() function sorts an indexed array in descending order. Tip: Use the sort() function to sort an indexed array in ascending order.