How to Sort Associative Array By Value and Key in PHP

Last Updated on June 14, 2021 by Roshan Parihar

In this tutorial, learn how to sort associative array by value and key in PHP. The short answer is to use the functions asort() and arsort() to sort by values and ksort() and krsort() to sort by key. These are the pre-defined function in PHP for the sorting of arrays.

You can sort the associative arrays in ascending and descending orders according to your requirements. Let’s find out with the examples given below here to learn the methods.

How to Sort Associative Array By Value in PHP

The sorting of an associative array by value uses the values of each item to arrange them in proper sequence. Let’ find out the different functions to arrange items of the array in PHP.

Ascending Order Using asort()

To arrange the associative array elements in ascending order by value, you can use the asort() that takes a single argument as an array variable.

Output

Array ( [Cycles] => 2 [Bikes] => 5 [Audi] => 9 [Ducati] => 10 )

The above example contains the array variable that contains the elements with alphabetical keys and numeric values. The output shows that the sequence of array elements changes to ascending order by value.

Descending Order Using arsort()

To change the sequence of an associative array element in descending order by value, you can use the arsort(). It takes a single argument as an associative array variable.

Output

Array ( [Ducati] => 10 [Audi] => 9 [Bikes] => 5 [Cycles] => 2 )

The output shows that the elements of an array are arranged in descending order by value.

Sorting By Key in PHP

The sorting of an associative array by key uses the keys of each item to make a proper sequence. Let’ find out what are the different functions to sort items of the array in PHP.

Ascending Order Using ksort()

To set the sequence of the associative array elements in ascending order by key, you can use the ksort() function that takes a single argument as the array variable. It is the built-in function of PHP for sorting array elements by keys.

Output

Array ( [Audi] => 9 [Bikes] => 5 [Cycles] => 2 [Ducati] => 10 )

The above example contains an output that shows keys are arrange in ascending order (A-Z).

Descending Order Using krsort()

To make the sequence of the associative array elements in descending order by key, you can use the krsort() function of PHP. It takes a single argument as the array variable to perform the task. See the example below that shows the use of the function.

Output

Array ( [Ducati] => 10 [Cycles] => 2 [Bikes] => 5 [Audi] => 9 )

The output shows that the keys are arrange in descending order (Z-A).

You May Also Like to Read

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.