If you need to sort based on a specific criteria, sort() may not work for you. In that case, usort() can be called upon.

Supply it with an array and the name of a function (which you must define in the script) and the array given will be re-indexed and contain the result.

To retain the keys, use uasort(). Use uksort() to sort by the keys using the algorithm supplied by your function.

The function must return an integer (or will be converted to an integer) greater than, equal to, or less than zero. This value will determine the first of the pair’s placement in respect to the other.

If they are equal, their placement is undetermined. This comes into play because the strings themselves may not be equal, but your function may say they are. If your function only compares the first character of the strings, for example, you can see how this might make a difference.

// Emulating sort() for this example
function cmp($a, $b) {
  $val = 0;
  if($a > $b) {
    $val = 1;
  } elseif($a < $b) {
    $val = -1;
  }
  return $val;
}
 
$arr = array(5,
             3,
             24,
             82,
             -34,
             7);
usort($arr, 'cmp');
/*
array (
  0 => -34,
  1 => 3,
  2 => 5,
  3 => 7,
  4 => 24,
  5 => 82
)
*/

The following example demonstrates how you can use this function to sort by last name given an array containing full names. Our comparison function here doesn’t account for all cases. We’re assuming that the last part of the string - when split up by the spaces - is the string we wish to compare. And that’s good enough for our example.

function cmp_last_name($a, $b) {
  // split them up by the space character
  $_1 = explode(' ', $a);
  $_2 = explode(' ', $b);
 
  // use the last part only (last name)
  $new_a = $_1[count($_1) - 1];
  $new_b = $_2[count($_2) - 1];
 
  // compare the new strings
  $val = 0;
  if($new_a > $new_b) {
    $val = 1;
  } elseif($new_a < $new_b) {
    $val = -1;
  }
 
  return $val;
}
 
$arr = array('Han Solo',
             'Lando Calrissian',
             'Leia Organa',
             'Luke Skywalker',
             'Obi-Wan Kenobi');
usort($arr, 'cmp_last_name');
/*
array (
  0 => 'Lando Calrissian',
  1 => 'Obi-Wan Kenobi',
  2 => 'Leia Organa',
  3 => 'Luke Skywalker',
  4 => 'Han Solo',
)
*/