PHP asort() Function: Sort Arrays by Value

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:

  1. Array: Required. Specifies the array to be sorted.
  2. 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
)
bannerAds