PHP Function Arsort - Sort Associative Arrays
Arrays are a powerful data structure in PHP which allows developers to store and manipulate multiple values in a single variable. Sorting is an important operation that can be performed on arrays in order to arrange them in a specific order. There are several built-in array functions in PHP that enable developers to sort arrays based on different parameters.
Sorting an array based on values can be done in various ways like ascending or descending order, alphabetical or numerical order, natural way or random way etc. In this article we will be discussing about the php function arsort which is used for sorting associative array in a way that keeps their original keys while performing the sort.
This function is an extension of usort and takes two parameters, the input array and the name of a user-defined compare function that will be called to compare the items in the array. The comparison function must return an integer value in order to be compatible with this function. Any non-integer value, such as a float, will be internally cast to an integer in order to be properly compared.
In the following example, we will use php function arsort to sort the $fruits array in a way that the relationships between the key and its associated value will be maintained while the array is sorted. The array will be sorted by the fruit names in reverse alphabetical order while maintaining their index association. This will make it easier to find the right item when we iterate through the array for each fruit.