Is there a simple way to take a list of numbers which can be in the range 1 - 15. And put a dash in place of consecutive numbers.
So that for example if you had the
$n = array (1, 2, 4, 5, 7, 8, 10, 11, 12, 13, 14, 16, 17);
$lastindex = count($n)-1;
foreach($n as $k => $i)
{
if($k == 0) echo $i;
elseif($i != $n[$k-1]+1) echo ', ' . $i;
elseif($k == $lastindex || $i+1 != $n[$k+1]) echo ' - ' . $i;
}
The function with explode:
http://codepad.org/DKztLGhe
function shorten( $numbers ){
$a = explode(' ',$numbers);
$lastindex = count($a)-1;
$s = '';
foreach( $a as $i => $n ){
if( $i == 0 ) $s .= $n;
else if( $a[$i-1]+1 != $n ) $s .= ', '.$n;
else if( $i == $lastindex || $n+1 != $a[$i+1] ) $s .= ' - '.$n;
}
return $s;
}
print_r(shorten('').'
');
print_r(shorten('1').'
');
print_r(shorten('1 2').'
');
print_r(shorten('1 3').'
');
print_r(shorten('1 3 4 6').'
');
print_r(shorten('1 3 4 6 7').'
');
print_r(shorten('1 2 3 4 5').'
');
print_r(shorten('1 2 3 5 6 10 12 13').'
');