PHP developers sometimes need to sort array values with a custom comparator while preserving their keys. This comes up when preparing data, displaying results, or integrating information with other services.
The uasort() operation handles this particular task. The following examples show its result, its limitations, and a practical way to apply it.
What Is uasort() in PHP?
Sort array values with a custom comparator while preserving their keys.
Its syntax is:
uasort(array &$array, callable $callback): true
The syntax shows the expected parameters and return type. Arguments marked with an ampersand are passed by reference and may be modified. Optional parameters control additional behavior; values must match the declared types.
Important: Callbacks must return negative, zero or positive integers; boolean comparators are incorrect. Original key associations are preserved.
Parameters:
&$array— May be updated by the function.$callback— A named input or configuration argument; use the declared type and optional default shown above.
Example 1: Basic Usage
This first example uses a small input to demonstrate the main result of uasort().
<?php
$scores = ["Maya" => 30, "Leo" => 10]; uasort($scores, fn($left, $right) => $left <=> $right); print_r($scores);
Output:
Array
(
[Leo] => 10
[Maya] => 30
)
The output demonstrates the primary operation: sort array values with a custom comparator while preserving their keys.
Example 2: Understanding Another Case
This second example changes the input or option to reveal a different behavior of uasort().
<?php
$names = ["first" => "Zoe", "second" => "amy"]; uasort($names, "strcasecmp"); print_r($names);
Output:
Array
(
[second] => amy
[first] => Zoe
)
Compared with the first example, this one illustrates the same operation with a different input shape or option. Callbacks must return negative, zero or positive integers; boolean comparators are incorrect. Original key associations are preserved.
Practical Example: A Real Application Scenario
Here is a practical use of uasort() with realistic sample information. Adapt the values to match your application.
<?php
$products = ["A" => 12, "B" => 7, "C" => 20]; uasort($products, fn($left, $right) => $right <=> $left); foreach ($products as $code => $price) { echo "$code: $price\n"; }
Output:
C: 20
A: 12
B: 7
This is a useful starting point, but production code should check errors and validate values before performing the operation. Callbacks must return negative, zero or positive integers; boolean comparators are incorrect. Original key associations are preserved.
Important Behavior and Edge Cases
Callbacks must return negative, zero or positive integers; boolean comparators are incorrect. Original key associations are preserved.
- Input: Use the expected PHP types and validate user-provided values.
- Result: Check the return value separately from any modifications to the input.
- Environment: For extension, database, or filesystem examples, verify availability and handle failures before accessing results.
Comparison With Related Functions
| Function or Approach | When to Use It |
|---|---|
uasort() | Sort array values with a custom comparator while preserving their keys. |
| Related functions | usort() renumbers keys; asort() uses built-in value comparison. |
Common Beginner Mistakes
| Mistake | Correct Approach |
|---|---|
| Expecting a sorted copy without changing the input | These sort functions modify the array directly; copy it first if you need the original. |
| Using the wrong sort target | Decide whether to sort keys or values, and whether key associations must remain intact. |
| Assuming every comparison handles text in the same way | usort() renumbers keys; asort() uses built-in value comparison. |
Key Takeaways
uasort()lets you sort array values with a custom comparator while preserving their keys.- Callbacks must return negative, zero or positive integers; boolean comparators are incorrect. Original key associations are preserved.
- usort() renumbers keys; asort() uses built-in value comparison.
- Check input, return values, and environmental requirements when adapting the examples.
uasort() provides a focused PHP operation for sort array values with a custom comparator while preserving their keys. Start with the simple examples, then adapt the practical example with the correct checks for your project.