How is the function asort in PHP used?
The function asort() is used to sort the values of an associative array in ascending order while maintaining the index relationship. Its syntax is as follows:
asort(array, sortingtype)
Explanation of parameters:
- Array: Required. Specifies the array to be sorted.
- You can choose the sorting type that determines how the values are compared:
SORT_REGULAR – Default. Compares values using the standard method.
SORT_NUMERIC – Compares values as numbers.
SORT_STRING – Compares values as strings.
For example, sorting the associative array by values in ascending order:
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
asort($age);
In the above example, the array $age will be sorted in ascending order based on the values, resulting in:
Array
(
[Peter] => 35
[Ben] => 37
[Joe] => 43
)