Sorting an associative array by value with asort()

The asort() function sorts an array such that array indices maintain their correlation with the array elements they are associated with. This is used mainly when sorting associative arrays where the actual element order is significant. asort() accepts an associative array and sorts its values just as sort() does. However, it preserves the array’s keys.

Example code:

 
$nums = array("one"=>5,"two"=>2,"three"=>1);
asort( $nums );
 
foreach ( $nums as $key => $val ) {
  print "$key = $val<br />";
}

We can reverse sort an associative array by value with arsort().

Share Article/Example:
  • DotNetKicks
  • DZone
  • StumbleUpon
  • Print
  • Add to favorites
  • Digg
  • del.icio.us
  • Twitter
  • Facebook
  • LinkedIn
  • Posterous
  • Slashdot

 

 
eXTReMe Tracker