PHP Tutorial - PHP usort() Function Sort the elements of the a array using a user-defined comparison function






Definition

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

Syntax

PHP usort() Function has the following syntax.

usort(array,myfunction);

Parameter

ParameterIs RequiredDescription
arrayRequired.Specifies the array to sort
myfunctionOptional.Name of comparison function.

myfunction must return an integer <, =, or > than 0 if the first argument is <, =, or > than the second argument.





Example

Sorts an array using a user-defined comparison function.


<?php//  w w  w .ja v a 2s . c o m
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");
?>




Example 2

The following code shows how to sort date format string value array.


<?php//from   www . j a v a2 s  .c  o m
$dates = array('10-10-2011', '2-17-2010', '2-16-2011', '1-01-2013', '10-10-2012');
function DateSort($a, $b) {

    // If the dates are equal, do nothing.
    if($a == $b) return 0;
    
    // Dissassemble dates
    list($amonth, $aday, $ayear) = explode('-',$a);
    list($bmonth, $bday, $byear) = explode('-',$b);

    // Pad the month with a leading zero if leading number not present
    $amonth = str_pad($amonth, 2, "0", STR_PAD_LEFT);
    $bmonth = str_pad($bmonth, 2, "0", STR_PAD_LEFT);

    // Pad the day with a leading zero if leading number not present
    $aday = str_pad($aday, 2, "0", STR_PAD_LEFT);
    $bday = str_pad($bday, 2, "0", STR_PAD_LEFT);

    // Reassemble dates
    $a = $ayear . $amonth . $aday;
    $b = $byear . $bmonth . $bday;

    // Determine whether date $a > $date b
    return ($a > $b) ? 1 : -1;
}

usort($dates, 'DateSort'); 

print_r($dates);
?>

The code above generates the following result.