Sorting an associative array by key using ksort()

The ksort php function sorts an array by key, maintaining key to data correlations. This is useful mainly for associative arrays. ksort() accepts an associative array and sorts its keys. The array passed is transformed and nothing is returned.

Example code:

$first = array("x"=>5,"a"=>2,"f"=>1);
ksort( $first );
 
foreach ( $first as $key => $val ) {
  print "$key = $val<br />";
}

krsort() can be used to reverse sort an associative array by key.

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

 

 
eXTReMe Tracker