Imagine you’re building a PHP application that manages a dictionary of terms, where each entry is stored in an associative array.
The keys are unique lowercase strings (like single letters or identifiers), and the values are corresponding words or phrases (e.g., [“a” => “Apple”, “b” => “Banana”, “c” => “Cherry”]). Our task is to create a function that sorts this array by the values (the words) in either ascending (A to Z) or descending (Z to A) order, while preserving the original key-value associations.
The function should also validate the sort order input to ensure it’s either “asc” or “desc”, throwing an error for invalid inputs.
The Code
Here’s the complete PHP function to achieve this:
PHP
<?php
function sortArrayByValue(array $inputArray, string $sortOrder = 'asc'): array {
// Validate sort order
$validOrders = ['asc', 'desc'];
if (!in_array(strtolower($sortOrder), $validOrders)) {
throw new InvalidArgumentException("Sort order must be 'asc' or 'desc'");
}
// Create a copy to avoid modifying the original array
$array = $inputArray;
// Sort while maintaining index association
if (strtolower($sortOrder) === 'asc') {
asort($array, SORT_STRING);
} else {
arsort($array, SORT_STRING);
}
return $array;
}
?>
How It Works
This function demonstrates key PHP sorting concepts, particularly for associative arrays. Let’s break it down step by step:
- Input Parameters:
- $inputArray: This is the associative array you want to sort (e.g., [“a” => “Apple”, “b” => “Banana”]).
- $sortOrder: A string indicating the sort direction, defaulting to ‘asc’. It accepts ‘asc’ for ascending or ‘desc’ for descending.
- Validation:
- We convert $sortOrder to lowercase using strtolower() to make the check case-insensitive.
- We use in_array() to verify if it’s one of the allowed values (‘asc’ or ‘desc’).
- If invalid, it throws an InvalidArgumentException with a clear error message. This teaches good practice in input validation to prevent unexpected behavior.
- Copying the Array:
- We create a copy of $inputArray to avoid modifying the original array passed by reference. This is important in PHP because arrays are passed by reference by default in functions.
- Sorting Logic:
- For ascending order (‘asc’), we use asort($array, SORT_STRING).
- asort() sorts the array by values while maintaining the key associations (unlike sort(), which reindexes numeric keys).
- SORT_STRING ensures string comparison, treating values as strings (e.g., “Apple” comes before “Banana”).
- For descending order (‘desc’), we use arsort($array, SORT_STRING).
- arsort() works like asort() but in reverse order.
- These functions sort in-place, modifying $array directly, which is why we made a copy earlier.
- For ascending order (‘asc’), we use asort($array, SORT_STRING).
- Return Value:
- The sorted array is returned, ready for use. The original keys remain intact, but the order of elements is now based on the sorted values.
This highlights PHP’s built-in sort functions: asort() and arsort() are ideal for value-based sorting in associative arrays, preserving keys unlike ksort() (which sorts by keys) or sort() (which discards keys).
Expected End Result
Let’s test the function with an example array: $testArray = [‘c’ => ‘Cherry’, ‘a’ => ‘Apple’, ‘b’ => ‘Banana’]; (note the unsorted order).
- Ascending Sort (sortArrayByValue($testArray, ‘asc’)):
- Output: [‘a’ => ‘Apple’, ‘b’ => ‘Banana’, ‘c’ => ‘Cherry’]
- Explanation: Values are sorted alphabetically (“Apple” first, then “Banana”, then “Cherry”), with keys preserved.
- Descending Sort (sortArrayByValue($testArray, ‘desc’)):
- Output: [‘c’ => ‘Cherry’, ‘b’ => ‘Banana’, ‘a’ => ‘Apple’]
- Explanation: Values are sorted in reverse alphabetical order (“Cherry” first, then “Banana”, then “Apple”), keys intact.
If you pass an invalid sort order like ‘random’, it throws: Error: Sort order must be ‘asc’ or ‘desc’.
You can try this in a PHP environment (PHP 8.4 or compatible) by adding example usage code like in the commented section of the function.
