Tutorialspoint.dev

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 relation between indices and values is maintained.

Syntax:

bool ksort( $array, $sorting_type )

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

  • $array: This parameter specifies the array which needs to be sorted. It is a mandatory parameter.
  • $sorting_type: This is an optional parameter. There are different sorting types which are discussed below:
    • SORT_REGULAR: The value of $sorting_type is SORT_REGULAR then items are compare normally.
    • SORT_NUMERIC: The value of $sorting_type is SORT_NUMERIC then items are compared numerically.
    • SORT_STRING: The value of $sorting_type is SORT_STRING then items are compared as a string.
    • SORT_LOCALE_STRING: The value of $sorting_type is SORT_STRING then items are compares as string, based on current locale.

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 differet 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" ";
}
  
?>

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 differet 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" ";
}
  
?>

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



This article is attributed to GeeksforGeeks.org

leave a comment

code

0 Comments

load comments

Subscribe to Our Newsletter