Current Location: Home> Latest Articles> Use asort() to sort the results in ascending order of occurrence frequency

Use asort() to sort the results in ascending order of occurrence frequency

M66 2025-06-07

In PHP, it is very common to process arrays, where array_count_values() and asort() are two very useful functions. The array_count_values() function can count the frequency of each element in an array, while the asort() function can sort ascendingly according to the value of the array. This article will introduce how to use these two functions in combination to arrange the array in ascending order according to the frequency of the elements.

1. Use array_count_values() to count the frequency

First, we need an array and then use the array_count_values() function to count the number of occurrences of each element. array_count_values() returns an associative array where the key is the element in the array and the value is the number of times the element appears.

Sample code:

 <?php
$array = ['apple', 'banana', 'orange', 'apple', 'banana', 'apple'];

$frequency = array_count_values($array);

print_r($frequency);
?>

Output:

 Array
(
    [apple] => 3
    [banana] => 2
    [orange] => 1
)

In the example above, we can see that apple appears 3 times, banana appears 2 times, and orange appears 1 time.

2. Use asort() to sort the frequency in ascending order

Next, we can use the asort() function to sort the array_count_values() results. The asort() function sorts the array ascending order based on the values ​​in the array, but keeps the key value associated.

Sample code:

 <?php
$array = ['apple', 'banana', 'orange', 'apple', 'banana', 'apple'];

$frequency = array_count_values($array);

// Arrange in ascending order of frequency
asort($frequency);

print_r($frequency);
?>

Output:

 Array
(
    [orange] => 1
    [banana] => 2
    [apple] => 3
)

As shown above, asort() sorts the array from low to high according to frequency.

3. Summary

By combining array_count_values() and asort() , we can sort very easily according to the frequency of the elements in the array. array_count_values() is used to count frequency, while asort() is responsible for sorting the frequency ascending order. You can use these functions to process and analyze data, especially in scenarios where you need to be sorted by frequency.

Things to note

  • asort() is sorted by value, if you want to sort by key, you can use ksort() .

  • If the array contains multiple elements of the same frequency, asort() will sort them according to the order in the original array.

The above is the basic method of how to use asort() and array_count_values() to sort arrays by frequency ascending order. If you need to count the frequency and sort it during development, remember to refer to the sample code in this article.