phparrayssorting

Explode a string of comma-separated date values then sort them


I have the following string which I am trying to explode and sort from earliest date to latest date:

$dates = '2010-11-05,2010-11-05,2010-11-06,2010-11-06,2010-11-07,2010-11-07,2010-11-08';

I've obviously tried sort(explode(',', $dates)); as well as usort, setting different sort flags, but this just returns true.

Which array sorting function am I looking for?


Solution

  • <?php
    
    $dates = '2010-11-05,2010-11-05,2010-11-06,2010-11-06,2010-11-07,2010-11-07,2010-11-08';
    
    $array = explode(',', $dates);
    sort($array);
    
    print_r($array);
    

    If you look carefully at the manual page for sort() you'll see that it receives its argument by reference:

    bool sort ( array &$array [, int $sort_flags = SORT_REGULAR ] )
    

    If you don't feed it with a variable, the results of the sorting will be lost since they can't be stored anywhere.