Wednesday, February 25, 2009

Sorting an array by time, date, month or year


function date_compare($x, $y){
  $x = strtotime($x);
  $y = strtotime($y);
  if ($x == $y) return 0;
  return (($x > $y)?1:-1);
}
$array = array (
 'Jan 01, 2008',
 'Oct 31, 2008',
 'Nov 01, 2008',
 'Dec 01, 2008',
 'Jul 01, 2008',
 'Aug 01, 2008',
 'Sep 01, 2008'
);

Before sorting print the array

print_r($array);

Now Sort the array

usort($array, 'date_compare');

After sorting print the array

print_r($array);

No comments: