Mr B
Mr B

Reputation: 4130

How do PHP array comparison functions work?

I have the following function:

public static function CompareGroupReportEntries($a, $b)
{
    if ($a->visibility == $b->visibility) {
        return 0;
    } else{
        return $a->visibility < $b->visibility ? 1 : -1;        
    }
}

It works fine and I understand what it does. However I have difficulty in understanding it how it works. It is called on the following line;

usort($reports, "Utilities::CompareGroupReportEntries");

It is called outside of a loop, so how does it manage to sort all the objects in the array? What are the parameters $a and $b for?

Appreciate the help.

Upvotes: 1

Views: 340

Answers (3)

lovesh
lovesh

Reputation: 5391

The function usort is a sorting function which takes an array and a callback function. here your function CompareGroupReportEntries is a callback function. PHP doesnt care whether your array elements are nubers or strings. it expects your callback function for the sorting criteria of the values of your array. iIf u are familiar with C then there is a quicksort function which also takes a callback function

Upvotes: 0

Catalin
Catalin

Reputation: 868

YOur answer here: PHP's USORT Callback Function Parameters

Upvotes: 1

Fender
Fender

Reputation: 3055

it compares the elements of the array to determine their position.

so $a and $b are to elements of the list and from the result of the CompareGroupReportEntries-function it can say which value is bigger, so it can move it one up or down

Upvotes: 0

Related Questions