Script that takes array of numbers (yrs,pgs,etc)& returns: 2000-2004, 2006, 2008-2010

Discussion in 'PHP' started by matrocka, Jan 28, 2010.

  1. #1
    Hi All:

    I'm looking for a script that would take an array of numbers and combine consecutive numbers and list non-consecutive numbers, sort of how the Print option in microsoft word works.

    I.e.

    I have an array that has the following numbers (1,2,3,5,6,7,9,12,13,14,19,22,23) - I am looking for a function that would return:

    1-7,9,12-14,19, 22-23

    Thanks,

    Mat
     
    matrocka, Jan 28, 2010 IP
  2. jestep

    jestep Prominent Member

    Messages:
    3,659
    Likes Received:
    215
    Best Answers:
    19
    Trophy Points:
    330
    #2
    This is a little ugly, but it should work.

    
    
    $values = array(1,2,3,5,6,7,9,12,13,14,19,22,23);
    
    $output = '';
    
    
    for($i=0;$i<count($values);$i++) {
        
        if(!$start) {
            $start = $values[$i];
        }
        
        if($values[$i+1] != $values[$i] + 1) {
    
            $end = $values[$i];
            
            if($start != $end) {
                $output .= $start.'-'.$end;
            } else {
                $output .= $end;
            }
            
            if($i != count($values)-1) {
                $output .= ',';
            }
            
            unset($start);
        }
    }
    
    //echo $output;
    //Output's 1-3,5-7,9,12-14,19,22-23
    
    
    PHP:
     
    jestep, Jan 28, 2010 IP