In five minutes I made a pretty ugly looking function. Can you help before I have to commit the code into history?
Requirements:
I would like a function that takes an array of numbers, and returns an array of ranges. Ideally remove the duplicate line.
Sample Input:
Array(1,2,3,4,5,6,10,11,12,13,20,24)
Output:
Array ( [0] => 1-6 [1] => 10-13 [2] => 20 [3] => 24 )
Winning Entries:
Pseudo code PHP
My attempt:
$myArray = array(1,2,3,4,5,6,10,11,12,13,20,24);
$rangeArray = array();
$start = $end = current($myArray);
foreach($myArray as $range){
if($range - $end > 1){
$rangeArray[] = ($start == $end)?$start:$start."-".$end;
$start = $range;
}
$end = $range;
}
$rangeArray[] = ($start == $end)?$start:$start."-".$end;
print_r($rangeArray);