Open In App

PHP ksort() Function

The ksort() function is an inbuilt function in PHP which is used to sort an array in ascending order according to its key values. It sorts in a way that the relationship between the indices and values is maintained.

Syntax:



bool ksort( $array, $sorting_type )

Parameters: This function accepts two parameters as mentioned above and described below:

Return Value: This function returns True on success or False on failure.



Below programs illustrate the ksort() function in PHP.

Program 1:




<?php
// PHP program to illustrate
// ksort()function
  
// Input different array elements
$arr = array("13" =>"ASP.Net",
             "12" =>"C#",
             "11" =>"Graphics",
             "4" =>"Video Editing",
             "5" =>"Photoshop",
             "6" =>"Article",
             "4" =>"Placement",
             "8" =>"C++",
             "7" =>"XML",
             "10" =>"Android",
             "1" =>"SQL",
             "2" =>"PL/Sql",
             "3" =>"End",
             "0" =>"Java",       
        );
  
// Implementation of ksort()
ksort($arr);
  
// for-Loop for displaying result
foreach ($arr as $key => $val) {
    echo "[$key] = $val";
    echo"\n";
}
  
?>

Output:
[0] = Java
[1] = SQL
[2] = PL/Sql
[3] = End
[4] = Placement
[5] = Photoshop
[6] = Article
[7] = XML
[8] = C++
[10] = Android
[11] = Graphics
[12] = C#
[13] = ASP.Net

Program 2:




      
<?php
// PHP program to illustrate
// ksort function
      
// Input different array elements
$arr = array("z" => 11,
             "y" => 22,
             "x" => 33,
             "n" => 44,
             "o" => 55,
             "b" => 66,
             "a" => 77,
             "m" => 2,
             "q" => -11,
             "i" => 3,
             "e" => 56,
             "d" => 1,                            
        );
  
// Implementation of ksort
ksort($arr);
  
// for-Loop for displaying result
foreach ($arr as $key => $val) {
    echo "[$key] = $val";
    echo"\n";
}
  
?>

Output:
[a] = 77
[b] = 66
[d] = 1
[e] = 56
[i] = 3
[m] = 2
[n] = 44
[o] = 55
[q] = -11
[x] = 33
[y] = 22
[z] = 11

Related Articles:

Reference: http://php.net/manual/en/function.ksort.php


Article Tags :