Sort: Fight fire with fire

Lets just cut to the chase. We have the following array:

$to_sort =  array(
  array("firstname" => "John", "lastname" => "Montgomery"),
  array("firstname" => "Anna", "lastname" => "Belluci"),
  array("firstname" => "Mary", "lastname" => "John"),
);

We need to sort it by last name. sort() wont help… The result array will be sorted by firstname. We can use usort(). But then, why we don’t use sort in our custom sorting function? I think it’s more correct than using lesser than (<) or greater than (>) as string operators (“ala” < "bala").

function sort_me($a, $b)
{
  $test = $mark = array($a['lastname'], $b['lastname']);
  sort($test);
 
  if ($mark != $test)
    return 1;
  return -1;
}
 
usort($to_sort, 'sort_me');

And the result:

Array
(
    [0] => Array
        (
            [firstname] => Anna
            [lastname] => Belluci
        )
 
    [1] => Array
        (
            [firstname] => Mary
            [lastname] => John
        )
 
    [2] => Array
        (
            [firstname] => John
            [lastname] => Montgomery
        )
 
)

The same as when lesser/greater than operators were used.

Leave a Comment


NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">