Skip to Main Content

Sort by Last Name First in PHP

This is less of a post, and more of a useful snippet. I’ve seen many posts online about sorting an array of names by surname, and they’ve all failed to be complete. Here is my addition to the pile. Keep in mind that it has known issues with compound last names that contain a space, like “Von Zinger”, “Mac Innis”, or “Di Vece”. However, it is a more robust solution than many others online today.

2 Comments

  1. Capt. Chawrls's profile image.
    Capt. Chawrls says:

    Thank you for posting this, it was very helpful. Below is a slightly modified version of you code that fixes the compund last name problem you mentioned.

    $name){
    $num_spaces = substr_count($name, ' ');
    if($num_spaces > 1){
    $kaboom = explode(' ', $name);
    $first = array_shift($kaboom);
    $last = implode('---', $kaboom);
    $names[$index] = $first . ' ' . $last;
    }
    }
    /* sort the names now */
    usort($names, function($a, $b) {
    // explode name a by spaces
    $parts_a = explode(' ', $a);
    // remove the last name from the end of the array
    $last_a = array_pop($parts_a);
    // and shove it on the front
    array_unshift($parts_a, $last_a);
    // then re-implode into a string
    $a = implode(' ', $parts_a);
    // repeat the process for name b
    $parts_b = explode(' ', $b);
    $last_b = array_pop($parts_b);
    array_unshift($parts_b, $last_b);
    $b = implode(' ', $parts_b);
    // perform a case insensitive string comparison
    return strcasecmp($a, $b);
    });
    /* remove temporary placeholder(s) */
    foreach($names as $index => $name){
    $names[$index] = str_replace('---', ' ', $name);
    }
    /* show the results */
    var_dump($names);

    • gschoppe's profile image.

      Unfortunately, because of the ambiguity inherent in naming, and the many conflicting standards, this won’t actually make the situation better, and on average, probably makes things worse. Consider the following list of names:

      • Gregory John Schoppe – Last Name: Schoppe
      • Victor Von Frankenstein – Last Name: Von Frankenstein
      • Billy Bob Thornton – Last Name: Thornton
      • J R R Tolkein – Last Name: Tolkein
      • L. Ron Hubbard – Last Name: Hubbard
      • Cher – Last Name: N/A
      • Helena Bonham Carter – Last Name: Bonham Carter
      • Robert the Bruce – Last Name: N/A

      The worst part is that none of these even represent particularly uncommon entries in a name field. Here is a great article listing some of the real edge cases that show up in a sufficiently large database of names:

      https://www.kalzumeus.com/2010/06/17/falsehoods-programmers-believe-about-names/

Your email address will not be published.

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>