Home >>PHP Array Functions >PHP ksort() Function

PHP ksort() Function

PHP ksort() Function

PHP ksort() function is used to sort any given array in ascending order according to its key values. It sorts in such a way that the relation between indexes and values is maintained. It accepts two parameters $array and $sort type. It returns a Boolean value True on success and False on failure.

Syntax:

ksort($array, $sorttype);

Parameter Values

Parameter Description
array This is a required parameter. It defines the array to sort.
sorttype sorttype This is an optional parameter. It defines how to compare the array elements.

Here is an example of ksort() function in PHP:

<html>
<body>
<?php
$a=array("A"=>"53","B"=>"73","C"=>"76");
ksort($a);
foreach($a as $x=>$x_value)
   {
   echo "Key=" . $x . ", Value=" . $x_value;
   echo "<br>";
   }
?>
</body>
</html>
Output:
Key=A, Value=53
Key=B, Value=73
Key=C, Value=76

Example 2:

<html>
<body>
<?php
$a=array("A","B","H","I","M","A","N","Y","U");
echo "Sorted using the ksort(): <br>";
ksort($a);
foreach($a as $x=>$x_value)
   {
   echo "Key=" . $x . ", Value=" . $x_value;
   echo "<br>";
   }
echo "<br>Sorted using the krsort(): <br>";
krsort($a);
foreach($a as $x=>$x_value)
   {
   echo "Key=" . $x . ", Value=" . $x_value;
   echo "<br>";
   }   
?>
</body>
</html>
Output:
Sorted using the ksort():
Key=0, Value=A
Key=1, Value=B
Key=2, Value=H
Key=3, Value=I
Key=4, Value=M
Key=5, Value=A
Key=6, Value=N
Key=7, Value=Y
Key=8, Value=U
Sorted using the krsort():
Key=8, Value=U
Key=7, Value=Y
Key=6, Value=N
Key=5, Value=A
Key=4, Value=M
Key=3, Value=I
Key=2, Value=H
Key=1, Value=B
Key=0, Value=A

No Sidebar ads