Custom Sorting with 'usort'
Part of the Logic & Flow section of Coddy's PHP journey — lesson 25 of 68.
When PHP's built-in sorting functions don't meet your specific needs, the usort() function provides the ultimate flexibility by allowing you to define exactly how elements should be compared and ordered. This function takes your array and a custom comparison function that you write to determine the sorting logic.
The comparison function receives two elements from the array and must return an integer: a negative number if the first element should come before the second, zero if they're equal, or a positive number if the first should come after the second.
<?php
function compareByLength($a, $b) {
return strlen($a) - strlen($b);
}
$words = ["elephant", "cat", "butterfly", "dog"];
usort($words, "compareByLength");
print_r($words);
// Outputs: Array ( [0] => cat [1] => dog [2] => elephant [3] => butterfly )
?>In this example, the comparison function calculates the difference between string lengths. When strlen($a) - strlen($b) returns a negative number, it means the first string is shorter and should come first in the sorted array.
Like other PHP sorting functions, usort() modifies the original array directly. This powerful function opens up possibilities for sorting by any criteria you can imagine—whether it's string length, custom business logic, or complex multi-field comparisons.
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 array of product prices in JSON format. Read the input, convert the JSON string to an array, create a comparison function that sorts prices in ascending order, use usort() with your comparison function to sort the array, and print the sorted array using print_r().
Input format: One line containing a JSON array of numbers (example: [29.99,15.50,42.00,8.75,33.25])
Expected output: The sorted array in ascending order by price, displayed using print_r()
Cheat sheet
The usort() function allows custom sorting by accepting a comparison function that defines the sorting logic.
The comparison function receives two elements and must return:
- Negative number: first element comes before second
- Zero: elements are equal
- Positive number: first element comes after second
<?php
function compareByLength($a, $b) {
return strlen($a) - strlen($b);
}
$words = ["elephant", "cat", "butterfly", "dog"];
usort($words, "compareByLength");
print_r($words);
// Outputs: Array ( [0] => cat [1] => dog [2] => elephant [3] => butterfly )
?>Like other PHP sorting functions, usort() modifies the original array directly.
Try it yourself
<?php
// Read input
$input = fgets(STDIN);
$prices = json_decode($input, true);
// TODO: Create a comparison function and use usort() to sort the array
// Output the sorted array
print_r($prices);
?>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