- implode: documentation ( source)
<?php
$arr = array(1,2,3,7);
$last_val = "";
$first_val = "";
$add_val = true;
foreach ($arr as $key => $value) {
if($first_val == "")
$first_val = $value;
if(isset($arr[$key+1]))
{
if($value+1 == $arr[$key+1])
{
$last_val = $arr[$key+1];
$add_val = false;
}
else
$add_val = true;
}
else
$add_val = true;
if($add_val)
{
if($last_val != "")
$datarange[] = $first_val."-".$last_val;
else
$datarange[] = $first_val;
$first_val = "";
$last_val = "";
}
}
echo implode(",", $datarange);