I have an array as follows:
Array(
[27] => 'Sarah Green',
[29] => 'Adam Brown',
[68] => 'Fred Able'
);
I’d like to sort it by surname and preserve the keys:
Array(
[68] => 'Fred Able'
[29] => 'Adam Brown',
[27] => 'Sarah Green'
);
Some names may have more than two first names, but it’s always the very last name I want to sort on.
What would be the best way to do this in PHP?
You can use the
uasortfunction, which allows you to specify a custom sorting method while also preserving keys:Here’s a demo.