Introduction

Recently, I’ve been refactoring a lot of business code. With my OCD tendencies, I wanted to straighten out the code left by my predecessors. However, the classes in ‘use’ statements are always sorted by name, resulting in uneven lengths and chaotic ordering that looks very frustrating.

So I Googled “PHPStorm use sort by length”. To my surprise, many people have the same requirement. A foreign netizen provided a solution, but upon checking, it not only required payment but also wasn’t very smooth to operate.

I continued searching, and heaven rewards those who persevere - I finally found the answer on someone’s Twitter: it turns out that PHPStorm has had this setting built-in since 2019.

Setting

Open PHPStorm preferences, then click Editor > Code Style > PHP > Code Conversion, find Sort 'use' statements below, and change the setting from the default Alphabetically to By length.

PHPStorm sorting setting

Then click OK and you’re done. Try it now - select your code and click Code > Reformat Code in the menu bar or press the shortcut keys Option + Command + L.

Summary

After this setting is complete, classes that are automatically imported during subsequent coding will be automatically sorted according to this sorting method, without the need to execute Reformat Code again.

I hope this is helpful, Happy hacking…