The array is a data structure commonly used in all programming languages because it allows developers to store related data in a cluster. Sometimes, arrays contain too many values, and managing them becomes intricate. To simplify this, PHP introduced various array sorting functions that help organize lists. In this tutorial, you will learn specifically about using the PHP ksort() function.
PHP ksort() Function
PHP's ksort() function is a predefined array sorting function that helps sort an associative array in ascending order based on the keys of the array.
bool ksort(array &$array, [, int $flag = SORT_REGULAR ]);
- Here, you can see that the function takes two parameters. The first parameter is an input array and is mandatory.
- The second parameter is the flag, which is optional. It can be used to modify the sorting behavior by defining the type of sorting. There are four types of sorting:
Sort Flag Description 0 or SORT_REGULAR Mode having value zero for comparing items normally. 1 or SORT_NUMERIC Mode having value one is implemented for comparing items numerically. 2 or SORT_STRING Mode having value two is implemented for comparing items as strings. 3 or SORT_LOCALE_STRING Mode having value three is implemented for comparing items as current locale strings. 4 or SORT_NATURAL Mode having value four is implemented for comparing items as strings (but with natural ordering).
This ksort() function returns 'true' when sorting is done successfully or returns 'false' if a failure occurs. This function does not return a sorted array; rather, it is used for sorting the input array.
For example, you can have an array of students' total marks, and you want to sort it in ascending order.
<?php $Marks= array("Trisha"=>350, "Steve"=>400, "Alex"=>320); ksort($Marks); print_r($Marks); //Print array ?>
Array ( [Alex] => 320 [Steve] => 400 [Trisha] => 350 )