PHP uasort() Function

Example

Sort the elements of the array $arr by key value using a user-defined comparison function:

<?php
function my_sort($a,$b)
{
if ($a==$b) return 0;
return ($a<$b)?-1:1;
}
$arr=array("a"=>4,"b"=>2,"c"=>8,d=>"6");
uasort($arr,"my_sort");
?>

Run Example

Definition and Usage

The uasort() function sorts an array using a user-defined comparison function and keeps index association (does not assign new keys to elements).

Returns TRUE if successful, FALSE otherwise.

This function is mainly used to sort combined arrays where the order of units is very important.

Hint:Use uksort() The function sorts an array by key name using a user-defined comparison function.

Syntax

uasort(array,myfunction);
Parameter Description
array Required. Specifies the array to be sorted.
myfunction Optional. A string defining a callable comparison function. If the first parameter is less than, equal to, or greater than the second parameter, the comparison function must return an integer less than, equal to, or greater than 0.

Technical Details

Return Value: Returns TRUE if successful, FALSE otherwise.
PHP Version: 4+