php group numbers into intervals

php group numbers into intervals

The article php group numbers into intervals will explain how to group the provided numbers in to intervals.

 

function group_nums($array) {
  $ret = array();
  $temp = array();
  foreach($array as $val) {
    if(next($array) == ($val + 1))
      $temp[] = $val;
    else
      if(count($temp) > 0) {
        $temp[] = $val;
        $ret[] = $temp[0].’:’.end($temp);
        $temp = array();
      }
      else
        $ret[] = $val;
    }
  return $ret;
}

$nums = array(1, 2, 3, 4, 14, 21, 23, 28, 29);
print_r(group_nums($nums));

// OUTPUT 
Array
(
    [0] => 1-4
    [1] => 14
    [2] => 21
    [3] => 23
    [4] => 28-29
)

 

Leave a Reply

Your email address will not be published. Required fields are marked *