PHP/Data Structure/usort
Sorting an Array Using Comparison Functions
<source lang="html4strict">
<?php
function evenfirst($i, $j) { $value = 0; if($i % 2)$value++; if($j % 2)$value--; if($value == 0) $value = $i < $j; return $value; } $clothes = array( "hats" => 75, "coats" => 32, "shoes" => 102, "gloves" => 15, "shirts" => 51, "trousers" => 44); usort($clothes, "evenfirst"); var_export($clothes);
?>
</source>
usort() sorts an array based on your own predefined criteria.
<source lang="html4strict">
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
"; }
?>
</source>