ksort()
In this article, we will discuss the ksort() function in PHP. The ksort() function is used to sort an array by key in ascending order. We will go through the
PHP Function: Array ksort()
In this article, we will discuss the ksort() function in PHP. The ksort() function is used to sort an array by key in ascending order. We will go through the syntax, parameters, and return value of this function, and provide some examples to help you understand it better. Let's dive into it. (Note: For reverse order sorting, PHP provides the krsort() function, which is demonstrated in Examples 2 and 4.)
Syntax
Syntax of ksort() function in PHP
ksort($array, $sorting_type);Parameters
The ksort() function takes two parameters:
$array: Required. Specifies the array to be sorted.$sorting_type: Optional. Specifies the sorting type, which can be one of the following constants:SORT_REGULAR(default, compares normally),SORT_NUMERIC(compares numerically),SORT_STRING(compares as strings),SORT_NATURAL(compare as strings using "natural ordering"), orSORT_LOCALE_STRING(compare as strings based on current locale).
Note: ksort() modifies the original array in-place and does not return a new array.
Return Value
The ksort() function returns a boolean value, true on success, and false on failure.
Example 1: Sorting an Associative Array by Key
Example of sorting an Associative Array by Key in PHP
<?php
$age = ["Peter" => "35", "Ben" => "37", "Joe" => "43"];
ksort($age);
print_r($age);Output:
Array
(
[Ben] => 37
[Joe] => 43
[Peter] => 35
)Example 2: Sorting an Associative Array by Key in Reverse Order
Example of sorting an Associative Array by Key Reverse Order in PHP
<?php
$age = ["Peter" => "35", "Ben" => "37", "Joe" => "43"];
krsort($age);
print_r($age);Output:
Array
(
[Peter] => 35
[Joe] => 43
[Ben] => 37
)Example 3: Sorting an Indexed Array by Key
<?php
$colors = ["red", "green", "blue", "yellow"];
ksort($colors);
print_r($colors);Output:
Array
(
[0] => red
[1] => green
[2] => blue
[3] => yellow
)Example 4: Sorting an Indexed Array by Key in Reverse Order
Example of sorting an Indexed Array by Key in Reverse Order in PHP
<?php
$colors = array("red", "green", "blue", "yellow");
krsort($colors);
print_r($colors);Output:
Array
(
[3] => yellow
[2] => red
[1] => green
[0] => blue
)Conclusion
In this article, we have discussed the ksort() function in PHP, which is used to sort an array by key in ascending order. We have gone through its syntax, parameters, and return value, and provided some examples to help you understand it better. We hope this article has been useful to you. If you have any questions or suggestions, please feel free to leave a comment below.
graph TD
A[PHP array] -->|ksort| B[Sorted PHP array]Practice
What is the purpose of the ksort() function in PHP?