PHP ksort is an inbuilt Function in PHP. It sorts arrays in ascending order according to keys while maintaining the relationship between keys and values. The smallest key in the input array appears first and the largest appears last. In this article, we will discuss the PHP ksort Function. Also, we will discuss a few examples of using it.
In order to sort an array in descending order by key, you can use PHP krsort Function.
bool ksort( $array, $sortingType = SORT_REGULAR )
The PHP ksort Function expects two parameters. However, only the first parameter is mandatory.
- $array: The first parameter to the function is an array which you need to sort by key. Also, it is a mandatory parameter.
- $sortingType: The function provides sorting types which are optional to pass. This parameter can take the following values:
- SORT_REGULAR: On passing SORT_REGULAR or 0, the function compares the elements normally without changing their type. Also, this is the default value to the parameter.
- SORT_NUMERIC: On passing SORT_NUMERIC or 1, the function compares the elements numerically.
- SORT_STRING: The function compares the elements string-wise on passing SORT_STRING or 2.
- SORT_LOCALE_STRING: The function compares the elements as a string based on current locale on passing SORT_LOCALE_STRING or 3. It uses the locale which can be changed by the setlocale function.
The PHP ksort Function returns true on success and false on failure. However, it modifies the original input array by soring it in ascending order on keys.
Note: The function preserves the keys of the original array after sorting. Also, if two values are equal, their relative order in the sorted array is undefined.
Let’s discuss a few examples of using the ksort Function in PHP.
Example 1: Sort Integer Array in Ascending Order By Keys
<?php $testArray = array(1 => 5, 0 => 6, 4 => 3, 3 => 2, 2 => 1); ksort($testArray); print_r($testArray); /* Array (  => 6  => 5  => 1  => 2  => 3 ) */ ?>
You should observe that the function sorts the array on keys in ascending order.
Example 2: Sorting String Keys
Similarly, you can also sort an array having string keys.
<?php $testArray = array("z" => 1, "y" => 2, "x" => 3, "n" => 4, "o" => 5, "b" => 6); ksort($testArray); print_r($testArray); /* Array ( [b] => 6 [n] => 4 [o] => 5 [x] => 3 [y] => 2 [z] => 1 ) */ ?>
In conclusion, we discussed the PHP ksort Function in this article. It sorts an array in ascending order on the basis of keys. You can read more about it on the Official PHP Documentation. Also, you can learn about more PHP Array Functions on Concatly.
Vishesh is currently working as a Senior Software Engineer at Naukri.com. He passed out of Delhi College of Engineering in 2016 and likes to play Foosball. He loves traveling and is an exercise freak. His expertise includes Java, PHP, Python, Databases, Design and Architecture.