Array Functions
Advertisements

PHP uksort() Function

Topic: PHP Array ReferencePrev|Next

Description

The uksort() function sorts an array by keys using a user-defined comparison function.

The keys are preserved, i.e. the key-to-value mapping will remain unchanged by the sort operation.

The following table summarizes the technical details of this function.

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

Syntax

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

uksort(array, compare_function);

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

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

// Sample array
$numbers = array("a"=>1, "c"=>2, "f"=>3, "d"=>4, "b"=>5, "e"=>6);

// Sort numbers array using compare function
uksort($numbers, "compare");
print_r($numbers);
?>

The uksort() function is mainly used for sorting associative arrays by key. To sort an associative array by values using a user-defined comparison function use the uasort() function.

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


Parameters

The uksort() 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.
Advertisements
Bootstrap UI Design Templates

Your Feedback:

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