Search code examples
phparrayssorting

How to naturally sort dates formatted as "Y_\mn"


I have an API returning a kind of date formatted as follow:

  • 2010_m1 for Jan 2010
  • 2010_m2 for Feb 2010
  • ...
  • 2010_m12 for Dec 2010

I have all the dates in an array, and if I use the method sort, it will sort it like:

[
    '2010_m1',
    '2010_m10',
    '2010_m11',
    '2010_m12',
    '2010_m2',
    '2010_m3',
    ...
]

How could I sort it the 'correct way', ie:

[
    '2010_m1',
    '2010_m2',
    '2010_m3',
    ...
    '2010_m10',
    '2010_m11',
    '2010_m12'
]

Solution

  • It's called natural sorting: natsort() is the PHP function for it.