Delicious Bookmark this on Delicious Share on Facebook SlashdotSlashdot It! Digg! Digg



PHP : Function Reference : Array Functions : ksort

ksort

Sort an array by key (PHP 4, PHP 5)
bool ksort ( array &array [, int sort_flags] )

Example 311. ksort() example

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

The above example will output:

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

Related Examples ( Source code ) » ksort




Code Examples / Notes » ksort

06-nov-2006 01:26

Why not just use built-in PHP functions? You can do an in-place natural sort by keys with:
uksort($array, 'strnatcasecmp');


ssb45

The function that justin at booleangate dot org provides works well, but be aware that it is not a drop-in replacement for ksort as is.  While ksort sorts the array by reference and returns a status boolean, natksort returns the sorted array, leaving the original untouched.  Thus, you must use this syntax:
$array = natksort($array);
If you want to use the more natural syntax:
$status = natksort($array);
Then use this modified version:
function natksort(&$array) {
$keys = array_keys($array);
natcasesort($keys);
foreach ($keys as $k) {
$new_array[$k] = $array[$k];
}
$array = $new_array;
return true;
}


sbarnum

ksort on an array with negative integers as keys yields some odd results.  Not sure if this is a bad idea (negative key values) or what.

richard dot quadling

Just to complete the comments made by ssb45.
If the supplied array is an empty array, the value returned is NOT an array.
All that is required is to pre-initialize the result.
function natksort(&$aToBeSorted)
{
$aResult = array();
$aKeys = array_keys($aToBeSorted);
natcasesort($aKeys);
foreach ($aKeys as $sKey)
{
$aResult[$sKey] = $aToBeSorted[$sKey];
}
$aToBeSorted = $aResult;
return True;
}


erikjr

Just a short note on "don dot hosek at gmail dot com" remark, the ksort returns TRUE or FALSE and performs its actual operation directly on the array in the function call.
Thus; it would be
<?php
ksort ( $a );
?>
instead of
<?php
$a = ksort ( $a );
?>
as noted in his piece. I didn't understand why my sorting kept returning '1' at first, but that was it.


don dot hosek

It's worth noting that ksort is also handy if you want to be able to do manipulations on an numerically-keyed array which may not have been initialized in numerical order:
$a[2]=7;
$a[0]=1;
$a[1]=6;
foreach($a as $b) {
 echo "$b ";
}
$a = ksort($a);
foreach($a as $b) {
 echo "$b ";
}


yaroukh

I believe documentation should mention which of array-functions do reset the internal pointer; this one does so ...

justin

Here's a handy function for natural order sorting on keys.
function natksort($array) {
 // Like ksort but uses natural sort instead
 $keys = array_keys($array);
 natsort($keys);
 foreach ($keys as $k)
   $new_array[$k] = $array[$k];
 return $new_array;
}


09-mar-2002 03:09

here 2 functions to ksort/uksort an array and all its member arrays
function tksort(&$array)
 {
 ksort($array);
 foreach(array_keys($array) as $k)
   {
   if(gettype($array[$k])=="array")
     {
     tksort($array[$k]);
     }
   }
 }
function utksort(&$array, $function)
 {
 uksort($array, $function);
 foreach(array_keys($array) as $k)
   {
   if(gettype($array[$k])=="array")
     {
     utksort($array[$k], $function);
     }
   }
 }


maxx

Beware! The function removes the keys with an empty value from the array. :-(

delvach

A real quick way to do a case-insensitive sort of an array keyed by strings:
uksort($myArray, "strnatcasecmp");


pedromartinez

A list of directories can be listed sorted by date (newer first) with this script. This is usefull if the directories contain (for example) pictures and you want the newer to appear first.
$maindir = "." ;
$mydir = opendir($maindir) ;
// SORT
$directorios = array();
while (false !== ($fn = readdir($mydir)))
{
if (is_dir($fn) && $fn != "." && $fn != "..")
{
$directory = getcwd()."/$fn";
$key = date("Y\-m\-d\-His ", filectime($directory));
    $directorios[$key] = $directory;
}
}
ksort($directorios);
$cronosdir = array();
$cronosdir = array_reverse($directorios);
while (list($key, $directory) = each($cronosdir)) {
   echo "$key = $directory<bR>";
}
Pedro


Change Language


Follow Navioo On Twitter
array_change_key_case
array_chunk
array_combine
array_count_values
array_diff_assoc
array_diff_key
array_diff_uassoc
array_diff_ukey
array_diff
array_fill_keys
array_fill
array_filter
array_flip
array_intersect_assoc
array_intersect_key
array_intersect_uassoc
array_intersect_ukey
array_intersect
array_key_exists
array_keys
array_map
array_merge_recursive
array_merge
array_multisort
array_pad
array_pop
array_product
array_push
array_rand
array_reduce
array_reverse
array_search
array_shift
array_slice
array_splice
array_sum
array_udiff_assoc
array_udiff_uassoc
array_udiff
array_uintersect_assoc
array_uintersect_uassoc
array_uintersect
array_unique
array_unshift
array_values
array_walk_recursive
array_walk
array
arsort
asort
compact
count
current
each
end
extract
in_array
key
krsort
ksort
list
natcasesort
natsort
next
pos
prev
range
reset
rsort
shuffle
sizeof
sort
uasort
uksort
usort
eXTReMe Tracker