PHP usort() Function

Example

Sort the elements of the array $a using a user-defined comparison function:

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

Run Example

Definition and Usage

usort() sorts an array using a user-defined comparison function.

Syntax

usort(array,myfunction);
Parameters Description
array Required. Specifies the array to be sorted.
myfunction Optional. Defines a string that specifies the name of 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.

Description

usort() function sorts an array using a user-defined function.

Note:If two elements have the same comparison result, the order of the elements in the sorted array is undefined. Before PHP 4.0.6, user-defined functions would preserve the original order of these elements. However, due to the introduction of a new sorting algorithm in 4.1.0, this is no longer the case because there is no effective solution for this.

Note:This function is array Assigns a new key name to the elements. This will remove the original key names.

Technical Details

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