In this article, you will learn how to sort an associative array in ascending order according to the keys. The ksort() function returns an array in which the elements of the input associative array are sorted in ascending order according to their keys.
What is the syntax of the ksort() function in PHP?
ksort(array, sorttype)
Parameter | Description |
---|---|
array | The array to sort – Required |
sorttype | Optional. Specifies how to compare the array elements/items. SORT_STRING (default) – Compare elements as strings SORT_REGULAR – Compares normally without changing the type SORT_NUMERIC – Compare as numeric values SORT_LOCALE_STRING – Compare as a string according to the current locale |
Examples of ksort() function
Example 1. Sort the associative array in ascending order according to keys.
<?php
$age=array("Jawad"=>"24","Ahmad"=>"25","Sumerina"=>"39");
ksort($age);
?>