In php how does usort() function works
The function cmp
itself doesn't do the sorting. It just tells usort
if a value is smaller, equal or greater than another value. E.g. if $a = 5
and $b = 9
it will return 1 to indicate that the value in $b
is greater than the one in $a
.
Sorting is done by usort
.
The callback provided to the sorting functions in PHP have three return values:
0: both elements are the same
-1 (<0): the first element is smaller than the second
1 (>0): the first element is greater
Now, usort
probably uses some kind of quicksort or mergesort internally. For each comparison it calls your callback with two elements and then decides if it needs to swap them or not.