Sorting Anything

function compare($a, $b) {
  return $a - $b;
$a = array(4, 1345, 31, 222);
usort($a, 'compare');
echo implode(' < ', $a);

The usort function

bool usort ( array &$array , callable $cmp_function )

This function will sort an array by its values using a user-supplied comparison function. usort function returns true on success and false on failure. This fucntion accepts two parameters:

  1. array as input

  2. cmp_function the callback comparison function

If you do not want to limit yourself to the standard sorting functionality offered by PHP, you can write your own sorting algorithm. Internally, PHP uses the Quicksort algorithm to sort values in an array. For this to work, PHP has to know if two values are equal; in the latter case, PHP needs to find out which value is greater. So, to implement a custom sort, all that is required is a function that takes two parameters and returns:

  • A negative value if the first parameter is smaller than the second parameter

  • 0 if both parameters are equal

  • A positive value if the second parameter is smaller than the first parameter

The name of this function must be passed to usort()as a string! The rest of the work is done by PHP, as can be seen in the code. The comparison function used there is a very simple way to do a numeric sorting. By substracting the two values, the function returns the desired values: A positive number if the first parameter is larger than the second one, 0 if both parameters are equal, and a negative number otherwise.

The Quicksort algorithm is one of the fastest algorithms to sort elements. When sorting n elements, it uses up to n? comparisons to do so; however, on average, only n log n comparisons are needed, making it really quick. Quicksort uses a divide-and-conquer strategy: It splits a problem into several smaller subproblems that can be solved recursively. More information about this algorithm can be found at