Hướng dẫn
Quảng cáo

Hàm uksort() trong PHP

Hướng dẫn cách sử dụng hàm uksort() về mảng trong lập trình PHP

Tác dụng của hàm uksort()

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+


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

uksort(array, compare_function);

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

// 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");

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.


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.

Bài viết này đã giúp ích cho bạn?

Bài viết mới