I'm trying to understand how usort works. So I used this code:

<?php
function usort_cmp($a, $b) {
echo $a . "->" . $b . "<br />\n";

}

$arr = array(1,2,3,4);
usort($arr, "usort_cmp");

?>

Which results in the following output:
2->1
4->2
3->2
4->3

But I can't understand why this output is like it is?

Can someone explain to me why usort outputs this random looking comparison (though not really random cause it is the same every time I run the script).

    usort() calls the callback function with two array element values that it wants to compare so that it knows how to sort them relative to each other. It will keep iterating through various pairs of elements until it sorts them all out (I'm guessing it uses a "bubble sort" algorithm, though I'm not sure). As stated in the manual: "The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second."

    Since you're not actually returning anything, I'm guessing it treats each value as being equal to every other value. All you are seeing are the values that usort() has sent to the callback function in order to decide how to order the array.

      Write a Reply...