Generic selectors
Exact matches only
Search in title
Search in content
Post Type Selectors

Sort Array (Ascending Order), According to Value – asort()

Sort Array (Ascending Order), According to Value – asort()

Sorting Arrays in Ascending Order with PHP’s asort() Function


Sorting is a fundamental operation in programming, and PHP provides a variety of functions to make this task easy and efficient. One such function is asort(), which is specifically designed to sort an array in ascending order based on its values. In this article, we’ll explore the asort() function and learn how to use it to organize arrays in ascending order.

Understanding asort():

The asort() function in PHP is used to sort an associative array in ascending order based on its values, while maintaining the association between keys and values. This means that the keys of the array will remain associated with their corresponding values even after sorting.


asort($array, $sorting_type);
  • $array: The associative array you want to sort.
  • $sorting_type (optional): Specifies the type of sorting. It can take one of two constant values: SORT_REGULAR (default) for regular comparison or SORT_NUMERIC for numeric comparison.

Example Usage:

Let's consider a simple example to understand how asort() works: $grades = array("John" => 85, "Jane" => 92, "Bob" => 78, "Alice" => 95); asort($grades); // Display the sorted array foreach ($grades as $name => $grade) { echo "$name: $grade\n"; }

In this example, the asort function will sort the array based on the values in ascending order. The output will be:

Bob: 78
John: 85
Jane: 92
Alice: 95


The asort() function in PHP provides a convenient way to sort associative arrays in ascending order based on their values. This is particularly useful when maintaining a relationship between keys and values is essential.

When working with large datasets or more complex sorting requirements, PHP offers other sorting functions like sort() and usort(). These functions provide additional flexibility in sorting arrays based on various criteria.

In summary, the asort function is a valuable tool for developers working with PHP, allowing them to efficiently organize data in ascending order while preserving the integrity of key-value associations within an associative array.

Scroll to Top