I need to use the uasort() function, but I don’t get how to get the arguments in the function… The given example is not so clear for me. How does the cmp function gets his arguments? Someone care to explain?
<?php
// Comparison function
function cmp($a, $b) {
if ($a == $b) {
return 0;
}
return ($a < $b) ? -1 : 1;
}
// Array to be sorted
$array = array('a' => 4, 'b' => 8, 'c' => -1, 'd' => -9, 'e' => 2, 'f' => 5, 'g' => 3, 'h' => -4);
print_r($array);
// Sort and print the resulting array
uasort($array, 'cmp');
print_r($array);
?>
The order in which elements are picked from the array shouldn’t make any difference to the way in which your comparison function works.
uasortwill be applied until every element in your array is sorted based upon the comparison you apply to it in yourcmpfunction.Updated
If you really want to know how it’s sorted, looking at the PHP source, the array first has
zend_hash_sortapplied to it which uses thezend_qsortcomparison function which as far as I’m aware, just orders by value.Try changing your cmp function to the below to see what’s going on: