How does this callback example (php manual) work?
Question
In the example below from http://php.net/manual/en/function.usort.php, a callback function is called.
function cmp($a, $b)
{
if ($a == $b) {
return 0;
}
return ($a < $b) ? -1 : 1;
}
$x = array(3, 2, 5, 6, 1);
usort($x, "cmp");
foreach ($x as $key => $value) {
echo "$key: $value<br>";
}
I'm not specifically interested in usort, but it's in the example. My question is, what are the $a and $b arguments to the cmp function? usort is given $x which is an array, so I don't understand what's going on in cmp (the code is simple, but I don't know what the arguments are).
My imagination tells me that $a and $b both iterate the array in some way (the only way it could be sorted). Can somebody shed some light on this?
Solution
They are two elements from the array being compared to eachother. The comparison function should return 0 if the two elements are equal, less than 0 if $a < $b or greater than 0 if $a > $b
The second example on php.net Example #2 usort() example using multi-dimensional array illustrates this a little more.
Since each array index is an array itself with possibly numerous elements, it allows you to sort the array based on the index you want.
In these cases, you just have to know the the callbacks expect to receive 2 values to compare, since to sort the array, you compare 2 elements at a time until the list is sorted. See Quicksort or Bubble sort for more on sorting algorithms.
<?php
function cmp($a, $b)
{
// usort gives 2 values from the array to compare, $a and $b
// we compare the "fruit" index from each item so the array is
// ultimately sorted by fruit
return strcmp($a["fruit"], $b["fruit"]);
}
$fruits[0]["fruit"] = "lemons";
$fruits[1]["fruit"] = "apples";
$fruits[2]["fruit"] = "grapes";
usort($fruits, "cmp");
while (list($key, $value) = each($fruits)) {
echo "\$fruits[$key]: " . $value["fruit"] . "\n";
}