Sort Assoc Arrays by Value
Part of the Logic & Flow section of Coddy's PHP journey — lesson 22 of 68.
When working with associative arrays, you often need to sort them by their values while preserving the key-value relationships. PHP provides two specialized functions for this purpose: asort() for ascending order and arsort() for descending order.
Here's how asort() works to sort by values in ascending order:
<?php
$students = [
"Alice" => 85,
"Bob" => 92,
"Charlie" => 78,
"Diana" => 96
];
asort($students);
print_r($students);
// Outputs: Array ( [Charlie] => 78 [Alice] => 85 [Bob] => 92 [Diana] => 96 )
?>Notice how the grades are now arranged from lowest to highest, but each student's name remains correctly paired with their grade. This is the key advantage of asort() over regular sort()—it maintains the association between keys and values.
For descending order, arsort() works similarly but arranges values from highest to lowest:
<?php
arsort($students);
print_r($students);
// Outputs: Array ( [Diana] => 96 [Bob] => 92 [Alice] => 85 [Charlie] => 78 )
?>Both functions modify the original array directly, just like their indexed array counterparts. This makes them perfect for organizing data like student grades, product prices, or any scenario where you need to sort by value while keeping the key-value pairs intact.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
Challenge
EasyYou will receive one input: an associative array of employee names and their salaries in JSON format. Read the input, convert the JSON string to an array, use arsort() to sort the employees by salary in descending order (highest to lowest), and print the sorted array using print_r().
Input format: One line containing a JSON object with employee names as keys and salaries as values (example: {"John":45000,"Sarah":52000,"Mike":38000,"Lisa":61000})
Expected output: The sorted associative array in descending order by salary values, displayed using print_r()
Cheat sheet
Use asort() to sort associative arrays by values in ascending order while preserving key-value relationships:
<?php
$students = [
"Alice" => 85,
"Bob" => 92,
"Charlie" => 78,
"Diana" => 96
];
asort($students);
print_r($students);
// Outputs: Array ( [Charlie] => 78 [Alice] => 85 [Bob] => 92 [Diana] => 96 )
?>Use arsort() to sort associative arrays by values in descending order:
<?php
arsort($students);
print_r($students);
// Outputs: Array ( [Diana] => 96 [Bob] => 92 [Alice] => 85 [Charlie] => 78 )
?>Both functions modify the original array directly and maintain the association between keys and values, unlike regular sort().
Try it yourself
<?php
// Read input
$input = fgets(STDIN);
// Convert JSON to associative array
$employees = (array)json_decode($input, true);
// TODO: Write your code below to sort the array by salary in descending order
// Output the sorted array
print_r($employees);
?>This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Advanced Functions
Anonymous FunctionsClosures and 'use'Arrow FunctionsCallback FunctionsUsing 'call_user_func'Variable FunctionsPassing by ReferenceRecursive FunctionsRecap: Function Medley4Multi-dimensional Arrays
Creating a 2D ArrayAccessing 2D Array ElementsModifying 2D Array ElementsIterating with Nested Loops2D Associative ArraysRecap: Simple Grid Exercise2Advanced Array Manipulations
Adding with 'array_push'Removing with 'array_pop'Adding with 'array_unshift'Removing with 'array_shift'Merging Indexed ArraysMerging Associative ArraysExtracting with 'array_slice'Values with 'in_array'Keys with 'array_search'Recap: Playlist Exercise3Sorting Arrays
Sort Indexed Arrays AscendingSort Indexed Arrays DescendingSort Assoc Arrays by ValueSort Assoc Arrays by KeyNatural Order SortingCustom Sorting with 'usort'Recap: Leaderboard Sorting