Code Logo

Associative Array Sort

Published at24 Jul 2026
PHP Data Structures Medium 0 views
Like0

Write a PHP function that sorts an associative array by its values in ascending order while maintaining key-value associations. Return the sorted array.

Use asort() which sorts an associative array by values while maintaining key-value relationships. This is different from sort() which reindexes numeric keys, and ksort() which sorts by keys.

Medium difficulty because it requires understanding PHP's array sorting functions and their different behaviors: asort() vs ksort() vs sort(). Each has specific use cases for associative arrays.

PHP provides four main sorting functions for associative arrays: asort() sorts by values ascending, arsort() by values descending, ksort() by keys ascending, and krsort() by keys descending. Each maintains key-value associations.

Understanding the difference between sort() (reindexes), asort() (maintains keys), and usort() (custom comparator) is essential for effective PHP array manipulation.

PHP's asort() is a stable sort that maintains key-value associations, essential for associative arrays where keys carry meaning. The function modifies the array in place and returns true on success. For descending order by value, use arsort() instead.

Example Input & Output

Example 1
Input
[]
Output
[]
Example 2
Input
["x":5,"y":3,"z":4]
Output
["y":3,"z":4,"x":5]
Example 3
Input
["c":3,"a":1,"b":2]
Output
["a":1,"b":2,"c":3]
Example 4
Input
["a":1]
Output
["a":1]
Example 5
Input
["b":2,"a":1]
Output
["a":1,"b":2]

Algorithm Flow

Recommendation Algorithm Flow for Associative Array Sort
Recommendation Algorithm Flow for Associative Array Sort

Solution Approach

Call asort($arr) which sorts by values in ascending order. The function returns true/false but modifies the array by reference. After sorting, return the sorted array or use array_values() to get a sequential list of sorted values.

PHP's array sorting functions (asort, arsort, ksort, krsort) modify the original array. The 'a' prefix stands for associative (keeping key-value pairs), while the 'r' prefix means reverse order.

Edge cases include empty arrays, arrays with equal values (keys maintain original relative order), and nested arrays as values.

Best Answers

php - Approach 1
<?php
function sortByValue($arr) {
    asort($arr);
    return $arr;
}