Can't understand the usort algorithm, how the user defined function gets the arguments

Hi,
Kindly see the program on the following link:
usort example

<?php function list_cmp($a, $b)
{
   global $order;
   foreach($order as $key => $value)
   {
      if($a==$value)
     {
        return 0;
        break;
    }
    if($b==$value)
   {
      return 1;
      break;
   }
}
}
$order[0] = 1; $order[1] = 3;  $order[2] = 4;  $order[3] = 2;  $array[0] = 2; $array[1] = 1;  $array[2] = 3;  $array[3] = 4;  $array[4] = 2;  $array[5] = 1;  $array[6] = 2;  

usort($array, "list_cmp");  print_r($array);  ?>

We are not passing values of $a and $b. How list_cmp(…) will get their values?

Zulfi.

all array sorting functions are passed two parameters under the hood; you notice you dont have to specify to walk through the entire array either.

PHP takes care of the arrangement of ‘walk the array; for each pair of elements, compare and sort.’ your function then must take 2 parameters (the two individual items being sorted at that given moment), and return a value that PHP can use to do the actual sorting.

Note that most comparison functions for sorting return what’s called a “Spaceship Operator Value” - namely, -1,0, or 1:

if -1, A goes before B.
if 0, A and B are of equal value, and are left unsorted relative to each other.
if 1, B goes before A.

You should imagine usort does something like this:

function usort($array, $callback) {
    // Get pairs of elements from $array and loop over them
    // Actual implementation of createPairsToSort is out of scope
    foreach ([$firstElement, $secondElement] = createPairsToSort($array)) {
        // Call the user defined function here to see how we should sort
        // these two elements
        $result = $callback($firstElement, $secondElement);

        if ($result < 1) {
            // update $array so $firstElement comes before secondElement
        } else if ($result === 0) {
           // keep elements in order, leave $array alone
        } else if ($result > 1) {
           // update $array so $firstElement comes after secondElement
        }
    }
}

For those who don’t know, the spaceship operator is <=>.

So in PHP 8 you can also sort like this:

usort($array, fn ($first, second) => $first <=> $second);

[quasi-off-topic]
I know it’s called a spaceship operator for the shape. But i’ve always seen it more like a seesaw. The pivot’s at 0, and it’s A (-1) and B (1) sitting on a seesaw, seeing which way it tips.
[/off-topic]

2 Likes