Home >>PHP Array Functions >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 | 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>
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>