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

Hàm usort() trong PHP

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

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

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+

Syntax

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

usort(array, compare_function);

The following example shows the usort() 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(2, 5, 4, 3, 6, 1);

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

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.


Parameters

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.

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

Bài viết mới

Advertisements