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.
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 says:
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:
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/