Geekality

Geekality

Search
Skip to content
Software Development

PHP: Natural sort array by a given key

February 3, 2017 Torleif Leave a comment

Just a note to self, after running around in google search circles for a bit…

function array_sort_by($key, array &$array)
{
    return usort($array, function($x, $y) use ($key)
    {
        return strnatcasecmp($x[$key] ?? null, $y[$key] ?? null);
    });
}

Uses ?? null in case key doesn’t exist on some items.

Switch to strnatcmp if you want case-sensitive sorting.

PHPSorting

Post navigation

Previous PostChoir practicing home alone with MusescoreNext PostEnabling query logging on MariaDB/MySQL

Greetings! I am Torleif Berger, and I’m a Software Engineer. I’m a Seventh-Day Adventist, an introvert, an ISFJ-T, and an HSP. Currently into forest hikes and indoor rock climbing; also dabble a bit with indoor rowing, juggling, and other fun activities, but most of my time is spent in front of a screen… c”,)

Stack Overflow

Google Twitter Facebook LinkedIn YouTube Vimeo RSS

Recent Posts

  • Node: Control depth when logging objects
  • Drop in use SQL Server database
  • How to clear local NuGet cache
  • How to find my actual login events in the Windows Event Viewer
  • Natural sort in Javascript
  • Git: Undo last commit
  • How to rename bluetooth device in Windows 10

Categories

Archives

Creative Commons License

With a hint of Social Ineptitude

Proudly powered by WordPress