From the description of usort ():
"The comparison function must return an integer that is less than, equal to, or greater than zero if the first argument is respectively smaller, equal to, or greater than the second."
Normal order should be considered ascending. If we want the usort function to consider the three as the smallest number - we must show -1 when it is the first argument, and +1 when it is the second.
And the rest - without anomalies.
$common = array(1,2,3,5,6); function cmp($a, $b) { if ($a == $b) return 0; if ($a == 3) return -1; if ($b == 3) return 1; return ($a < $b) ? -1 : 1; } usort($common, 'cmp'); var_dump($common);
array (size = 5)
0 => int 3
1 => int 1
2 => int 2
3 => int 5
4 => int 6
PS In addition, the result is the use of usort () with an anonymous comparison function:
$common = array(1,2,3,5,6); $num = 3; usort($common, function($a,$b) use($num){ if ($a == $b) return 0; if ($a == $num) return -1; if ($b == $num) return 1; return ($a < $b) ? -1 : 1; } ); var_dump($common);
In the above implementation, the number 3 is the context parameter specified by the use () option. This approach allows you to test the sorting for different values of the $ num parameter without much hassle.