Array Functions

PHP usort() Function

Topic: PHP Array ReferencePrev|Next


The usort() function sorts an array by values using a user-defined comparison function.

The following table summarizes the technical details of this function.

Return Value: Returns TRUE on success or FALSE on failure.
Version: PHP 4+


The basic syntax of the usort() function is given with:

usort(array, compare_function);

The following example shows the usort() function in action.

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

// Sample array
$numbers = array(2, 5, 4, 3, 6, 1);

// Sort numbers array using compare function
usort($numbers, "compare");

Note: The comparison function must return an integer equal to zero if both values are equal, an integer less than zero if the first value is less than the second value, and an integer greater than zero if the first value is greater than the second value.

Tip: The usort() function assigns new keys to the elements in array. It will remove any existing keys that may have been assigned, rather than just reordering the keys.


The usort() function accepts the following parameters.

Parameter Description
array Required. Specifies the array to be sorted.
compare_function Optional. Specifies the compare function to use for sorting.
Bootstrap UI Design Templates

Your Feedback:

We would love to hear from you, please drop us a line.