0

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] ?

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

6 Comments

As a general note: PHP uses a quicksort algorithm
don't get it. "They are just two of the elements from the array being sorted". Say in this case, $a is which element, $b is which?
@MarkBaker: I assumed it did, but couldn't prove it. Is that documented anywhere, or is that gleaned from looking at the source?
@gilzero: It could be any pair, in general. Take a look at how e.g. the quicksort algorithm or the bubblesort algorithm work; they all involve performing comparisons on arbitrary pairs of elements.
@MarkBaker @Oli PHP has a generic hashtable sorting function zend_hash_sort (lxr.php.net/xref/PHP_TRUNK/Zend/zend_hash.c#1421), but in practice it is always provided with a zend_qsort (lxr.php.net/xref/PHP_TRUNK/Zend/zend_qsort.c#56) sorting function (e.g. lxr.php.net/xref/PHP_TRUNK/ext/standard/array.c#536). So yeah, PHP uses quicksort :)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.