can some 1 explain this code :

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
pelegk2
Forum Regular
Posts: 633
Joined: Thu Nov 27, 2003 5:02 am
Location: Israel - the best place to live in after heaven
Contact:

can some 1 explain this code :

Post 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
pimp
Forum Newbie
Posts: 9
Joined: Sat Nov 06, 2004 10:22 am

Post 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.
User avatar
pelegk2
Forum Regular
Posts: 633
Joined: Thu Nov 27, 2003 5:02 am
Location: Israel - the best place to live in after heaven
Contact:

Post 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?
User avatar
mudkicker
Forum Contributor
Posts: 479
Joined: Wed Jul 09, 2003 6:11 pm
Location: Istanbul, TR
Contact:

Post by mudkicker »

this makes the comparison function.
usort compares the array members regareding this function.
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Post 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 .
Post Reply