What is the function uasort() in PHP and how can it be used for custom sorting?

The uasort() function in PHP is used to sort an array with a user-defined comparison function while maintaining key-value associations. This can be useful when you need to sort an array based on values, but still want to keep track of the original keys. To use uasort() for custom sorting, you need to define a callback function that compares the values of the array elements and then pass this function as a parameter to uasort().

// Define a custom comparison function
function custom_sort($a, $b) {
    if ($a == $b) {
        return 0;
    }
    return ($a < $b) ? -1 : 1;
}

// Sample array to be sorted
$fruits = array("apple" => 4, "orange" => 2, "banana" => 3);

// Sort the array using uasort() with the custom comparison function
uasort($fruits, "custom_sort");

// Print the sorted array
print_r($fruits);