<?php
function compound(array $arr)
{
$cache=array();
$rst="";
foreach($arr as $v)
{
if(empty($cache) || $v==end($cache)+1)
{
$cache[]=$v;
}
else
{
if(!empty($rst)) $rst.=",";
if(count($cache)>2) $rst.=reset($cache)."-".end($cache);
else $rst.=implode(",",$cache);
$cache=array($v);
}
}
if(!empty($rst)) $rst.=",";
if(count($cache)>2) $rst.=reset($cache)."-".end($cache);
else $rst.=implode(",",$cache);
return $rst;
}
echo compound(array(1,2,3,5,6))."\n"; // gets "1-3,5,6"
echo compound(array(1,3,4,5,6)); // gets "1,3-6"
preferences:
48.7 ms | 402 KiB | 5 Q