usort() sorts an array based on your own predefined criteria. : usort « Data Structure « PHP






usort() sorts an array based on your own predefined criteria.

 
Its syntax is: void usort(array array, string function_name)

<?
    $vocab = array("S123","A1234", "P12345", "A1234567","T");
    
    function compare_length($str1, $str2) {
         $length1 = strlen($str1);
         $length2 = strlen($str2);
    
         if ($length1 == $length2) :
              return 0;
         elseif ($length1 < $length2) :
              return -1;
         else :
              return 1;
         endif;
    }
    usort($vocab, "compare_length");
    
    while (list ($key, $val) = each ($vocab)) {
         echo "$val<br>";
    }
?>
  
  








Related examples in the same category

1.Sorting an Array Using Comparison Functions