I wrote this question in the comments in my previous question, but since this is a separate question - I ask it separately

let's say we have an array of the form: array(1, 2, 3, 5, 6) , it is necessary that 3 be in the first place - array(3, 1, 2, 5, 6) how can this be implemented through the cmp-функцию ?

  • one
    As far as I understand, this is a user-defined function called from the usort () function. I clarify this point, because user-defined functions may have a different name and be called from other functions. - Yuri Negometyanov

2 answers 2

I think the sort function should look like this:

 function cmp($a, $b) { if ($a == $b) return 0; if ($a == 3) return -1; if ($b == 3) return 1; return ($a < $b) ? -1 : 1; } $a = array(1, 2, 3, 5, 6); usort($a, "cmp"); echo "<pre>\n"; foreach ($a as $key => $value) { echo "$key: $value\n"; } echo "</pre>\n"; 

PS The example is taken from http://php.net/manual/ru/function.usort.php

UPD The verification procedure is so strange:

 $a = 3, $b = 2, $a = 6, $b = 3, $a = 5, $b = 3, $a = 1, $b = 3, $a = 2, $b = 3, $a = 1, $b = 2, $a = 6, $b = 1, $a = 5, $b = 1, $a = 2, $b = 1, $a = 5, $b = 2, $a = 6, $b = 5, 
  • Do not tell me how exactly this function works? Why does $a and $b recover and what will be stored in them? ($a, $b) - (1, 2), (1, 3), (1, 5), (1, 6) | (2, 1), (2, 2), (2, 3) (2, 5), (2, 6) и т.д. (1, 2), (1, 3), (1, 5), (1, 6) | (2, 1), (2, 2), (2, 3) (2, 5), (2, 6) и т.д. I understand correctly? - cmd
  • @ cmd, wrote in response. - Visman

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.