PHP uasort() Function

PHP

PHP uasort() - Custom Associative Sort

Welcome to this detailed tutorial on the PHP uasort() function. If you need to sort associative arrays in PHP using your own custom comparison logic while preserving the key-value relationship, uasort() is your go-to solution.

Introduction

The uasort() function in PHP allows developers to sort an array by values using a user-defined comparison function. Unlike usort(), which reindexes the array numerically, uasort() preserves the keys of the associative array. This makes it ideal when the association between keys and values is crucial.

Use case: You have an associative array where keys are identifiers (like IDs or names) and values are the data points you want to sort by custom criteria — for example, complex objects, nested arrays, or multi-field values.

Prerequisites

  • Basic knowledge of PHP syntax and arrays.
  • Understanding of anonymous functions or callable user-defined functions in PHP.
  • Access to a PHP 5.3+ environment (for anonymous functions support).

Setup Steps

  1. Ensure PHP is installed (version 5.3 or higher recommended).
  2. Create or load your associative array in PHP.
  3. Write a user-defined comparison function or anonymous function that returns an integer based on value comparison.
  4. Pass the array and comparison function to uasort().
  5. Use the sorted array as needed, now with original keys preserved.

Understanding PHP uasort() Syntax

bool uasort(array &$array, callable $value_compare_func)
  • &$array: The associative array you want to sort (passed by reference; the original array is modified).
  • $value_compare_func: A callback function that compares two values and returns an integer (< 0, 0, > 0) similar to strcmp() behavior.

Practical Examples

Example 1: Basic Alphabetical Sort by Values

Sort an associative array of usernames with their respective scores alphabetically by the username.

<?php
$users = [
    'john123' => 'John Doe',
    'anna45' => 'Anna Smith',
    'mike99' => 'Michael Johnson',
];

uasort($users, function($a, $b) {
    return strcmp($a, $b);
});

print_r($users);
/* Output:
Array
(
    [anna45] => Anna Smith
    [john123] => John Doe
    [mike99] => Michael Johnson
)
*/
?>

Example 2: Sorting by Numeric Values (Custom Comparison)

Sort an associative array of product IDs and their prices from lowest to highest while keeping the original keys.

<?php
$products = [
    'p1' => 29.99,
    'p2' => 9.99,
    'p3' => 49.50,
    'p4' => 15.00,
];

uasort($products, function($a, $b) {
    if ($a == $b) return 0;
    return ($a < $b) ? -1 : 1;
});

print_r($products);
/* Output:
Array
(
    [p2] => 9.99
    [p4] => 15
    [p1] => 29.99
    [p3] => 49.5
)
*/
?>

Example 3: Sorting by Complex Array Values

Suppose each value is an associative array with multiple fields. Sort by a specific nested value.

<?php
$employees = [
    101 => ['name' => 'John', 'age' => 28],
    102 => ['name' => 'Anna', 'age' => 22],
    103 => ['name' => 'Zara', 'age' => 35],
];

// Sort employees by age ascending, preserve keys
uasort($employees, function($a, $b) {
    return $a['age'] - $b['age'];
});

print_r($employees);
/* Output:
Array
(
    [102] => Array
        (
            [name] => Anna
            [age] => 22
        )
    [101] => Array
        (
            [name] => John
            [age] => 28
        )
    [103] => Array
        (
            [name] => Zara
            [age] => 35
        )
)
*/
?>

Best Practices

  • Always return an integer from your comparison function: less than zero if first argument is less, zero if equal, and greater than zero if greater.
  • Use anonymous functions for concise and reusable code.
  • Do not modify the array inside the comparison function to avoid inconsistency.
  • Test your comparison logic separately before using it in uasort() to avoid unexpected results.
  • Be mindful of type comparisons especially with numeric and string mixed values.

Common Mistakes

  • Not preserving the return value rules in comparison function (e.g., returning boolean true/false instead of integers).
  • Using usort() instead when keys must be preserved.
  • Modifying or reassigning the array inside the comparison callback.
  • Passing an invalid callback or wrong parameters to uasort().
  • Ignoring strict type comparisons leading to unexpected ordering.

Interview Questions

Junior-Level Questions

  • Q1: What does the uasort() function do in PHP?
    A: It sorts an associative array by values using a user-defined comparison function, preserving the original keys.
  • Q2: How does uasort() differ from usort()?
    A: uasort() preserves keys while sorting; usort() reindexes the array numerically.
  • Q3: What type of function is required as the second argument to uasort()?
    A: A callback function that compares two values and returns an integer indicating their order.
  • Q4: Can uasort() sort multidimensional arrays?
    A: Yes, if the comparison function is written to compare the specific nested values.
  • Q5: Does uasort() return a new sorted array?
    A: No, it sorts the given array in place and returns TRUE on success.

Mid-Level Questions

  • Q1: Why must the comparison function for uasort() return an integer?
    A: PHP relies on the integer (<0, 0, >0) return value to determine the sorting order of two elements.
  • Q2: How does uasort() behave when two values are equal?
    A: It maintains the original order between those equal values (stable sorting is not guaranteed though).
  • Q3: Provide an example comparison function for sorting associative array values as strings case-insensitively.
    A:
    function($a, $b) {
      return strcasecmp($a, $b);
    }
  • Q4: How does uasort() handle keys internally?
    A: The keys remain unchanged and associated with their values after sorting.
  • Q5: Can you use named functions instead of anonymous functions with uasort()?
    A: Yes, you can pass any callable function name.

Senior-Level Questions

  • Q1: Describe a scenario where uasort() is preferred over other array sorting functions.
    A: When sorting associative arrays with user-defined rules while maintaining keys, such as sorting user data by last login timestamps without losing user IDs.
  • Q2: How would you handle sorting by multiple nested fields using uasort()?
    A: Implement the comparison function to first compare the primary field; if equal, fall back to comparing secondary fields, mimicking multi-level sorting.
  • Q3: Discuss performance considerations when using uasort() on large arrays.
    A: Custom comparison functions might add overhead; keep them efficient and avoid heavy computation inside them to reduce sort time.
  • Q4: Can uasort() be used to sort objects inside associative arrays? How?
    A: Yes, the comparison function should access object properties and return comparison integers accordingly.
  • Q5: How does uasort() handle error cases or invalid comparisons?
    A: If the comparison function doesn't return consistent integer values, sorting behavior is unpredictable. PHP does not throw exceptions but may sort incorrectly.

Frequently Asked Questions (FAQ)

Q1: Can uasort() sort arrays by keys instead of values?

No, uasort() only sorts by values. Use uksort() when you want to sort associative array by keys with a user-defined function.

Q2: What happens if the callback returns true or false instead of an integer?

PHP expects an integer. Returning true/false may cause unpredictable behavior in sorting and is discouraged.

Q3: Is the sorting performed by uasort() stable?

No, PHP's built-in sorting functions, including uasort(), do not guarantee stable sorting (equal elements might change relative order).

Q4: Can I use uasort() on multidimensional arrays?

Yes, as long as the comparison function correctly accesses and compares the values you want to sort by, including nested array values.

Q5: How do I revert an array to its original order after using uasort()?

You need to store the original order (for example, keys or a copy of the array) before sorting, as uasort() modifies the array in place and does not keep history.

Conclusion

The PHP uasort() function is a powerful tool for sorting associative arrays with custom comparison logic, especially when maintaining key-value pairs is essential. With a clear understanding of how to create comparison functions and careful implementation, you can sort any associative array by complex criteria effectively.

Whether you're sorting simple strings, numbers, or complex nested arrays, mastering uasort() enhances your capability to handle and organize data within PHP applications efficiently.