Month: February 2025

php: powerful sorting with usort

i recently worked on a rescue project where the original dev wanted to sort an array of item objects first by manufacturer name and then by price, descending. their ‘solution’ was an eighty-line foreach mess of fiddling with array keys. it was difficult to read, more difficult to modify, and didn’t even work correctly lots of the time. i replaced the whole thing with a five-line usort call.

usort stands for ‘user-defined sort’. it allows us, as devs, to write our own sorting rules (plural!) and makes working with arrays of complex data easier.

in this post, we’re going to take a thorough look at sorting arrays with usort. we’ll go over the basics of how the function works, write some ascending and descending sorts on integers and strings, and then cover how to sort on multiple values.

best other sorting functions can do for you is one rule on an array of primitives
Continue reading →