Home > Articles > Data > MySQL

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Sorting Anything

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

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 whether 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—or, if you are using at least PHP 5.3, you can also rely on an anonymous function similar to JavaScript. The rest of the work is done by PHP, as shown 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.

  • + Share This
  • 🔖 Save To Your Account