search for in the  
<keyksort>
Last updated: Thu, 19 May 2005

krsort

(PHP 3 >= 3.0.13, PHP 4, PHP 5)

krsort -- Sort an array by key in reverse order

Description

bool krsort ( array &array [, int sort_flags] )

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

Returns TRUE on success or FALSE on failure.

Example 1. krsort() example

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

The above example will output:

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

You may modify the behavior of the sort using the optional parameter sort_flags, for details see sort().

See also asort(), arsort(), ksort(), sort(), natsort(), and rsort().



User Contributed Notes
krsort
peter at pmkmedia dot com
07-Nov-2003 03:51
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);
}
lolo at phpheaven dot net
28-Nov-2000 02:33
If you want to emulate the krsort function for an older version of php, you can use this piece of code:

function KeyComp($a, $b)

  return -(strcmp($a,$b));
}

function krsort($MyArray)
{
  uksort($MyArray, "KeyComp");
}

Maybe obvious and useless, but who knows...

<keyksort>
 Last updated: Thu, 19 May 2005
Copyright © 2001-2005 The PHP Group
All rights reserved.
This unofficial mirror is operated at: The Server Pages
Last updated: Thu May 19 17:35:34 2005 CDT