3v4l.org

run code in 300+ PHP versions simultaneously
<?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);

preferences:
26.23 ms | 402 KiB | 5 Q