$myArray[0] = 1;
$myArray[1] = 2;
$myArray[2] = 3;
$myArray[3] = 4;
$myArray[4] = 6;
$myArray[5] = 7;
$myArray[6] = 8;
$myArray[7] = 10;
$myArray[8] = 11;
$myArray[9] = 13;
$myArray[10] = 14;
$myArray[11] = 15;
$myArray[12] = 17;
$myArray[13] = 19;
$str = '';
$isRange = false;
for( $i = 0, $length = count( $myArray ); $i < $length; $i++ ) {
if( isset($myArray[ $i + 1 ] ) ) {
if( $myArray[ $i + 1 ] == $myArray[ $i ] + 1 ) {
if( $isRange ) {
continue;
}
$str .= $myArray[ $i ] . '-';
$isRange = true;
}
else {
$isRange = false;
$str .= $myArray[ $i ] . ',';
}
}
else {
$str .= $myArray[ $i ];
}
}
echo $str;
$myArray = Array(1,2,3,4,6,7,8,10,11,13,14,15,17,19);
$num = current($myArray);
$difference = $elements = 0;
$result = Array();
foreach ($myArray as $k=>$v) {
$prev = $k>0 ? $myArray[$k-1] : 0;
$difference += $v - $prev;
$elements++;
if ($difference > $elements) {
$result[] = $num . ($elements>1 && $prev ? '-' . $prev : '');
$num = $v;
$difference = $elements = 0;
}
}
// также добавить последний элемент или разницу между ним и последним запомненным
$result[] = $num . ($elements>1 && $v ? '-' . $v : '');
echo implode(',', $result);
<?php
function extractIntervals(array $data) {
$result = [array_shift($data)];
array_walk($data, function ($element) use (&$result) {
$i = count($result) - 1;
$j = count($result[$i]) - 1;
$diff = $element - $result[$i][$j];
if ($diff > 1) {
$result[$i][] = $element;
} else {
$result[] = [$element];
}
});
return $result;
}
function extractStringIntervals(array $data) {
return implode(', ', array_map(function (array $interval) {
$first = $interval[0];
$last = $interval[count($interval) - 1];
return $first == $last ? $first : ($first . '-' . $last);
}, extractIntervals($data)));
}