saiibitta
saiibitta

Reputation: 407

Sort array with month name and year in php

I have an array like

$ar =['March 2018',
      'March 2018',
      'November 2017',
      'December 2017',
      'January 2018',
      'January 2018',
      'February 2018'
     ];

I want to sort this array with month and year. But i unable to sort this array.

Expected Output: [
     'November 2017',
      'December 2017',
       'January 2018',
      'January 2018',
      'February 2018',
      'March 2018',
      'March 2018'
];

Tried with functions like usort(), uksort() .... but its not working Please help me to solve this issue

Upvotes: 2

Views: 1516

Answers (1)

Eddie
Eddie

Reputation: 26844

You can use usort and use strtotime to convert the string to time.

$ar = ['March 2018',
  'March 2018',
  'November 2017',
  'December 2017',
  'January 2018',
  'January 2018',
  'February 2018'
];

usort( $ar , function($a, $b){
    $a = strtotime($a);
    $b = strtotime($b);
    return $a - $b;
});

echo "<pre>";
print_r( $ar );
echo "</pre>";

This will result to:

Array
(
    [0] => November 2017
    [1] => December 2017
    [2] => January 2018
    [3] => January 2018
    [4] => February 2018
    [5] => March 2018
    [6] => March 2018
)

Upvotes: 5

Related Questions