ksort() Function in PHP

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.

Syntax:
bool ksort(array &$array, [, int $flag = SORT_REGULAR ]);

Parameters

  • 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 FlagDescription
    0 or SORT_REGULARMode having value zero for comparing items normally.
    1 or SORT_NUMERICMode having value one is implemented for comparing items numerically.
    2 or SORT_STRINGMode having value two is implemented for comparing items as strings.
    3 or SORT_LOCALE_STRINGMode having value three is implemented for comparing items as current locale strings.
    4 or SORT_NATURALMode having value four is implemented for comparing items as strings (but with natural ordering).

Return Value

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.

Example
<?php

$Marks= array("Trisha"=>350, "Steve"=>400, "Alex"=>320);

ksort($Marks);

print_r($Marks); //Print array

?>
Output
Array ( [Alex] => 320 [Steve] => 400 [Trisha] => 350 )

Scroll Back to Top