Reputation: 1902
Example:
<?php
function cmp($a, $b)
{
if ($a == $b) {
return 0;
}
return ($a < $b) ? -1 : 1;
}
$a = array(3, 2, 5, 6, 1);
usort($a, "cmp");
foreach ($a as $key => $value) {
echo "$key: $value\n";
}
?>
Result
0: 1
1: 2
2: 3
3: 5
4: 6
in the user defined compare function 'cmd
', it has two arguments, $a
& $b
.
What do the first and second argument represent? Are they array[x]
and array[x+1]
?
Upvotes: 0
Views: 604
Reputation: 272467
They are just two of the elements from the array being sorted, not necessarily neighbours. usort
performs some sort algorithm (see http://en.wikipedia.org/wiki/Sort_algorithm#Comparison_of_algorithms), which involves comparing various pairs of elements to determine their order. It uses your callback function to determine this.
Upvotes: 3