Sorting with a Comparison Function PHP

The built-in sorting functions are appropriate in the overwhelming majority of situations. If your problem requires a sort that performs better than the one used in the built-in functions, you are faced with coding your own. If your problem is that you need to compare complex elements, such as objects or multidimensional arrays, the solution is to write a comparison function and plug it into the usort function.

The usort function allows you to sort an array using your own comparison function. Your comparison function must accept two values and return an integer. The two arguments are compared, and if a negative number is returned, then the values are considered to be in order. If zero is returned, they are considered to be equal. A positive number signifies that the numbers are out of order.

In Listing I've created a multidimensional array with three elements: name, title, and wage. Sometimes I want to be able list employees by name, but other times I might want to list them by title or how much they make per hour. To solve this problem, I've written three comparison functions.

The byName function is a simple wrapper for strcmp. Names will be ordered by ASCII code. The byTitle function assigns an integer value to each title and then returns the comparison of these integers. The bySalary function compares the wage element, but if two employees make the same amount of money per hour, their names are compared.

Using the usort Function

Using the usort Function

The byName function is a simpler wrapper for strcmp. Names will be ordered by ASCIIcode. The byTitle function assigns an integer value to each title and then returns the comparison of these integers. The bySalary function compares the wage element, but if two employees make the same amount of money per hour, their names are compared.


All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

PHP Topics