Page 1 of 1

can some 1 explain this code :

Posted: Mon Nov 08, 2004 3:21 am
by pelegk2
i taoke this from usort() :

Code: Select all

<?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");
?>
how does or what execlly happens that the cmp function recives 2 varaibles?
and what execlly goes in this code?
thnaks in advance
peleg

Posted: Mon Nov 08, 2004 3:28 am
by pimp
this function will return -1 if a<b , 0 if they are equal and 1 if a>b. the <cond>?<expr1>:<expr> it's used for replacing if, where posible.if cond is true, then it return expr1 else expr2.
this function will sort the array using that function as the main algorithm.

Posted: Mon Nov 08, 2004 4:56 am
by pelegk2
yes i understand what cmp() does
i dont understand how execlly it recivies it values?does the usort(0 activate it and how does it sort it?

Posted: Mon Nov 08, 2004 5:01 am
by mudkicker
this makes the comparison function.
usort compares the array members regareding this function.

Posted: Mon Nov 08, 2004 7:20 am
by Weirdan
pelegk2 wrote: i dont understand how execlly it recivies it values?
it gets its parameters from internal zend_hash_sort function (which lies behind almost any array sorting function in php).
pelegk2 wrote: does the usort(0 activate it and how does it sort it?
Use the source, Luke :) zend_hash_sort is defined somewhere near Zend/zend_hash.c in PHP source tree .