PHP uasort() Function
Topic: PHP Array ReferencePrev|Next
Description
The uasort()
function sorts an array by values 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 uasort()
function is given with:
The following example shows the uasort()
function in action.
Example
Run this code »<?php
// Define comparison function
function compare($a, $b){
if($a == $b){
return 0;
}
return ($a < $b) ? -1 : 1;
}
// Sample array
$numbers = array("a"=>2, "b"=>-1, "c"=>7, "d"=>-9, "e"=>5, "f"=>-4);
// Sort numbers array using compare function
uasort($numbers, "compare");
print_r($numbers);
?>
The uasort()
function is mainly used for sorting associative arrays by value. To sort an associative array by keys using a user-defined comparison function use the uksort()
function.
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.
Parameters
The uasort()
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. |